【每日一题Day103】LC1669合并两个链表 | 模拟

简介: 思路:遍历链表找到list1中的第a−1个节点和第b+1个节点,然后将第a−1个节点指向list2链表的初始节点,list2链表的尾节点指向list1中的第b+1个节点

合并两个链表【LC1669】


You are given two linked lists: list1 and list2 of sizes n and m respectively.


Remove list1’s nodes from the ath node to the bth node, and put list2 in their place.


The blue edges and nodes in the following figure indicate the result:


295eca6b66038d4f9595e2bfa8d6a884.png


Build the result list and return its head.


  • 思路:遍历链表找到list1中的第a−1个节点和第b+1个节点,然后将第a−1个节点指向list2链表的初始节点,list2链表的尾节点指向list1中的第b+1个节点


  • 实现


/**
 * 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 dummyNode = new ListNode(-1, list1);
        ListNode pre = dummyNode;
        ListNode cur = dummyNode.next;
        int idx = 0;
        while (idx != a){
            pre = cur;
            cur = cur.next;  
            idx++;          
        }
        while (idx != b){
            cur = cur.next;
            idx++;
        }
        pre.next = list2;
        while (list2.next != null){
            list2 = list2.next;
        }
        list2.next = cur.next;
        cur.next = null;
        return list1;       
    }
}


。复杂度分析


  • 时间复杂度:O ( n )
  • 空间复杂度:O ( 1 )
目录
相关文章
《剑指offer》——合并两个排序的链表
《剑指offer》——合并两个排序的链表
251 0
|
Go
golang力扣leetcode 23.合并K个升序链表
golang力扣leetcode 23.合并K个升序链表
174 0
|
存储 人工智能 测试技术
每日练习之排序——链表的合并;完全背包—— 兑换零钱
每日练习之排序——链表的合并;完全背包—— 兑换零钱
234 2
23. 合并 K 个升序链表
23. 合并 K 个升序链表
219 3
|
Java C语言
剑指offer(牛客)——合并两个排序的链表
剑指offer(牛客)——合并两个排序的链表
177 1
反转链表、链表的中间结点、合并两个有序链表【LeetCode刷题日志】
反转链表、链表的中间结点、合并两个有序链表【LeetCode刷题日志】
|
Java Go C++
Golang每日一练(leetDay0114) 矩阵中的最长递增路径、按要求补齐数组
Golang每日一练(leetDay0114) 矩阵中的最长递增路径、按要求补齐数组
380 0
Golang每日一练(leetDay0114) 矩阵中的最长递增路径、按要求补齐数组
|
Java Go C++
Golang每日一练(leetDay0096) 添加运算符、移动零
Golang每日一练(leetDay0096) 添加运算符、移动零
288 0
Golang每日一练(leetDay0096) 添加运算符、移动零
|
C++ Python Java
Python每日一练(20230424) 滑动窗口最大值、栈实现队列、直线上最多的点数
Python每日一练(20230424) 滑动窗口最大值、栈实现队列、直线上最多的点数
811 0
Python每日一练(20230424) 滑动窗口最大值、栈实现队列、直线上最多的点数
|
Go C++ Java
C/C++每日一练(20230408) 删除无效括号、合并K个升序链表、四数之和
C/C++每日一练(20230408) 删除无效括号、合并K个升序链表、四数之和
265 0
C/C++每日一练(20230408) 删除无效括号、合并K个升序链表、四数之和