Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Pinterest
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Merge a Linked list into another Linked List at Alternate Positions.

Objec­tive: Given two linked lists, merge one list into another at alter­nate posi­tions, if sec­ond link list has extra nodes, print them as well

Exam­ple:

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 start­ing 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 temp node.
  • Print the remain­ing list in B, B will be point­ing to the head of the reman­ing list.

Com­plete Code:


Out­put:

->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

You may also like...