Table of Contents
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
1 2 3 |
<strong>Input:</strong> list1 = [10,1,13,6,9,5], a = 3, b = 4, list2 = [1000000,1000001,1000002] <strong>Output:</strong> [10,1,13,1000000,1000001,1000002,5] <strong>Explanation:</strong> 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
1 2 3 |
<strong>Input:</strong> list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004] <strong>Output:</strong> [0,1,1000000,1000001,1000002,1000003,1000004,6] <strong>Explanation:</strong> 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
Approach
- Get tail of list 2
- Get node a-1 and b+1
- Merge two lists by pointing list1 a-1.next to the head of list 2 and pointing the tail.next of list 2 to b+1 node of list 1
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
class Solution { public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) { //1.get tail of list 2 ListNode t2 = getTail(list2); //2. get node a-1 and b+1 ListNode aPrev = getPrevNode(list1, a); ListNode bNext = aPrev.next; int diff = b-a; int i=0; while(i<diff && bNext!=null){ bNext = bNext.next; i++; } //3. Merge two lists by pointing list1 a-1.next to the head of list 2 and pointing the tail.next of list 2 to b+1 node of list 1 aPrev.next = list2; t2.next = bNext.next; return list1; } private ListNode getTail(ListNode l){ while(l.next!=null){ l = l.next; } return l; } private ListNode getPrevNode(ListNode l, int a){ ListNode prev = null; int i=0; while(l!=null && i!=a){ prev = l; l = l.next; i++; } return prev; } } |