合并两个链表【LC1669】
You are given two linked lists:
list1andlist2of sizesnandmrespectively.Remove
list1’s nodes from theathnode to thebthnode, and putlist2in their place.The blue edges and nodes in the following figure indicate the result:
Build the result list and return its head.
-
思路:遍历链表找到
list1中的第a−1a-1a−1个节点和第b+1b+1b+1个节点,然后将第a−1a-1a−1个节点指向list2链表的初始节点,list2链表的尾节点指向list1中的第b+1b+1b+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(n)O(n)
- 空间复杂度:O(1)O(1)O(1)
-

本文介绍了一种将一个链表的指定部分替换为另一个链表的方法。通过定位目标节点,并调整节点指针来完成合并过程。该算法适用于单链表的数据结构。

2万+

被折叠的 条评论
为什么被折叠?



