Given two linked lists, merge their nodes into the first list by taking nodes alternately between the two lists. If the first list runs out, the remaining nodes of the second list should not be moved.

For example, consider lists {1, 2, 3} and {4, 5, 6, 7, 8}. Merging them should result in {1, 4, 2, 5, 3, 6} and {7, 8}, respectively.

Practice this problem

The solution depends on being able to move nodes to the end of a list. Many techniques are available to solve this problem: dummy node, local reference, or recursion.

1. Using Dummy Node

The strategy here uses a temporary dummy node as the start of the result list. The pointer tail always points to the last node in the result list, so appending new nodes is easy. The dummy node gives the tail something to point to initially when the result list is empty. This dummy node is efficient since it is only temporary, and it is allocated in the stack. The loop proceeds, removing one node from either a or b and adding it to the tail. When we are done, set a to dummy.next.

This approach is demonstrated below in C, Java, and Python:

C


Download  Run Code

Output:

First List: 0 —> 1 —> 2 —> 3 —> NULL
Second List: 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> NULL
 
After Merge:
 
First List: 0 —> 4 —> 1 —> 5 —> 2 —> 6 —> 3 —> 7 —> NULL
Second List: 8 —> 9 —> 10 —> NULL

Java


Download  Run Code

Output:

First List: 0 —> 1 —> 2 —> 3 —> null
Second List: 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> null
 
After Merge:
 
First List: 0 —> 4 —> 1 —> 5 —> 2 —> 6 —> 3 —> 7 —> null
Second List: 8 —> 9 —> 10 —> null

Python


Download  Run Code

Output:

First List: 0 —> 1 —> 2 —> 3 —> None
Second List: 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> None
 
After Merge:
 
First List: 0 —> 4 —> 1 —> 5 —> 2 —> 6 —> 3 —> 7 —> None
Second List: 8 —> 9 —> 10 —> None

2. Using Local References

This method uses a local reference to get rid of the dummy nodes entirely. Instead of using a dummy node, it maintains a struct node** pointer, lastPtrRef, which always points to the last pointer of the result list. This solves the same case that the dummy node did – dealing with the result list when it is empty. When trying to build up a list at its tail, either use the dummy node or the struct node** “reference” strategy. It uses moveNode() function as a helper.

Following is the C++ implementation of the idea:

C++


Download  Run Code

3. Recursive

The recursive solution is the most compact of all but is probably not appropriate for production code since it uses stack space proportionate to the lists’ lengths. The algorithm can be implemented as follows in C++:

C++


Download  Run Code

The time complexity of all above-discussed methods is O(m + n), where m and n are the total number of nodes in the first and second list, respectively.

 
References: http://cslibrary.stanford.edu/105/LinkedListProblems.pdf