Member-only story
Leetcode 1669: Merge In Between Linked Lists
In this Leetcode problem, we want to merge a list list2
into another list list1
and remove some elements of list1
where list2
is going.
Solution
We want to simply build the list simply by going to the node in list1
where list2
should be inserted. Then keep going in list1
to get to the node that should come after the last node of list2
.
Let’s look at an example:
list1 = [1, 2, 3, 4, 5];
list2 = [6, 7, 8];
a = 3;
b = 4;
We setup a list current
to go through list1
. After we go through the list to get the last node before insertion, we have:
list1 = [1, 2, 3, 4, 5];
list2 = [6, 7, 8];
a = 3;
b = 4;
current = [2, 3, 4, 5];
Then, after we de-reference current to list2 and remember the toRemove
node:
list1 = [1, 2, 6, 7, 8];
list2 = [6, 7, 8];
a = 3;
b = 4;
current = [2, 6, 7, 8];
toRemove = [3, 4, 5];
Then, we find the node to add back at the end of list2, and add it at the end of list2:
list1 = [1, 2, 6, 7, 8, 5];
list2 = [6, 7, 8, 5];
a = 3;
b = 4;
current = [2, 6, 7, 8, 5];
toRemove = [5];
Finally, this is the solution code, step by step:
class Solution {
public ListNode…