LeetCode 1669. Merge In Between Linked Lists
原题链接在这里:https://leetcode.com/problems/merge-in-between-linked-lists/description/
题目:
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:
Build the result list and return its head.
Example 1:
Input: list1 = [10,1,13,6,9,5], a = 3, b = 4, list2 = [1000000,1000001,1000002] Output: [10,1,13,1000000,1000001,1000002,5] Explanation: We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result.
Example 2:
Input: list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004] Output: [0,1,1000000,1000001,1000002,1000003,1000004,6] Explanation: The blue edges and nodes in the above figure indicate the result.
Constraints:
3 <= list1.length <= 104
1 <= a <= b < list1.length - 1
1 <= list2.length <= 104
题解:
when index hit a - 1, mark1, when hit b - 1, mark2.
mark1.next = list2.
Move list2 to the tail and point to mark2.next.
Time Compelxity; O(b + n). n = list2 length.
Space: O(1).
AC Java:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode() {} 7 * ListNode(int val) { this.val = val; } 8 * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 * } 10 */ 11 class Solution { 12 public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) { 13 ListNode cur = list1; 14 ListNode mark1 = null; 15 for(int i = 0; i < b; i++){ 16 if(i == a - 1){ 17 mark1 = cur; 18 } 19 20 cur = cur.next; 21 } 22 23 mark1.next = list2; 24 while(list2.next != null){ 25 list2 = list2.next; 26 } 27 28 list2.next = cur.next; 29 cur.next = null; 30 return list1; 31 } 32 }