Construct a linked list by merging alternate nodes of two given lists

Given two linked lists, merge their nodes together to make one list, taking nodes alternately between the two lists. If either list runs out, all the nodes should be taken from the other list.

 

For example,

Consider lists {1, 2, 3} and {7, 13, 1}. Merging them should yield {1, 7, 2, 13, 3, 1}.

 


 

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.

 

Dummy Node Not Using MoveNode()

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 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 tail. When we are done, the result is in dummy.next.

 
C++ implementation –
 

Download   Run Code

Output:

First List  – 1 -> 3 -> 5 -> 7 -> null
Second List – 2 -> 4 -> 6 -> null
After Merge – 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> null

 


 

Dummy Node Using MoveNode()

This method is logically same as above, but it use MoveNode() function as a helper.

 
C++ implementation –
 

Download   Run Complete Code

Output:

First List  – 1 -> 3 -> 5 -> 7 -> null
Second List – 2 -> 4 -> 6 -> null
After Merge – 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> null

 


 

Local References

This solution is structurally very similar to the above, but it avoids using a dummy node. Instead, it maintains a struct node** pointer, lastPtrRef, that 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. If you are trying to build up a list at its tail, either the dummy node or the struct node** “reference” strategy can be used.

 
C++ implementation –
 

Download   Run Complete Code

Output:

First List  – 1 -> 3 -> 5 -> 7 -> null
Second List – 2 -> 4 -> 6 -> null
After Merge – 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> null

 


 

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 lengths of the lists.

 
C++ implementation –
 

Download   Run Complete Code

Output:

First List  – 1 -> 3 -> 5 -> 7 -> null
Second List – 2 -> 4 -> 6 -> null
After Merge – 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> null

 

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

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz