leetcode1669. 合并两个链表(java)

合并两个链表

题目描述

难度 - 中等
leetcode1669. 合并两个链表

给你两个链表 list1 和 list2 ,它们包含的元素分别为 n 个和 m 个。
请你将 list1 中下标从 a 到 b 的全部节点都删除,并将list2 接在被删除节点的位置。
下图中蓝色边和节点展示了操作后的结果:
在这里插入图片描述请你返回结果链表的头指针。

示例1:
在这里插入图片描述
输入:list1 = [0,1,2,3,4,5], a = 3, b = 4, list2 = [1000000,1000001,1000002]
输出:[0,1,2,1000000,1000001,1000002,5]
解释:我们删除 list1 中下标为 3 和 4 的两个节点,并将 list2 接在该位置。上图中蓝色的边和节点为答案链表。

示例2:
在这里插入图片描述输入:list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004]
输出:[0,1,1000000,1000001,1000002,1000003,1000004,6]
解释:上图中蓝色的边和节点为答案链表。

提示:
3 <= list1.length <= 10^4
1 <= a <= b < list1.length - 1
1 <= list2.length <= 10^4

在这里插入图片描述

指针

链表问题,没什么难度,就是按要求把指针移动,重连出要求的样子,这里也是,先用一个指针记录下,a - 1位置的节点,然后继续往下走,找到b节点,最后把第二个链表的头尾节点按图中的方式连接起来就好了。
使用两个变量 pre 指向 list1第一个断联的位置,分别将 pre 指向 list2 的开头,将 list2 的 next 指针指向 list1。

代码演示

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    
    
    public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) {
    
    
        ListNode pre = null;
        ListNode head = list1;
        while(--a > 0 && --b > 0){
    
    
            list1 = list1.next;
        }
        pre = list1;
        while(b-- > 0){
    
    
            list1 = list1.next;
        }
     
        pre.next = list2;
        while(list2.next != null){
    
    
            list2 = list2.next;
        }
        list2.next = list1.next;
        return head;
    }
}

猜你喜欢

转载自blog.csdn.net/SP_1024/article/details/132874830