This post is completed by 1 user
|
Add to List |
Merge a Linked list into another Linked List at Alternate Positions.
Objective: Given two linked lists, merge one list into another at alternate positions, if second link list has extra nodes, print them as well
Example:
5 -> 10 -> 15 -> 20 ->25 -> null 3 -> 6 ->9 -> 12 ->15 ->18 ->21 -> null Output : 5 -> 3 -> 10 -> 6 ->15 -> 9 -> 20 -> 12 -> 25 ->15 -> null Remaining List : 18 -> 21 -> null
Approach:
- Say Node A and Node B are the starting of two linked list.
- Take Node temp = A ( store the head of the link list one).
- Take Node A1 = A.next and Node B1 = B.next;
- Make A.next points to the B.
- Make B.next = A1. (at this point B is inserted between A and A1).
- Do the above two steps till one of the list burns out.
- Print the list using the temp node.
- Print the remaining list in B, B will be pointing to the head of the remaining list.
Code:
Output:
->5->10->15->20->25 ->3->6->9->12->15->18 Alternate Mergred List ->5->3->10->6->15->9->20->12->25->15 Remaining Second List ->18
Also Read: