Merging of linked lists

In this article ,I will be discussing some problems based on merging of linked lists.


Problem statement : We had 2 linked lists - a1-a2-a3.....aN and b1-b2-b3..........bN
We want to merge it into a single linked list - a1-b1-a2-b2-a3-b3...........an-bn



Solution : We would be using the linked list we had already developed in previous blogs. I am again showing the structure of this list below :

There would be a simple function in this list which takes 2 nodes and merges them both into the main linked list.The given function is :
The simple strategy here is to iterate through the 2 lists and keep on adding current node of of each list to the original linked list. Below is a test program to test it.
One variation of the above problem could be to write a function in LinkedList class which accepts a linked list and merges it with itself.


Problem statement : Merging of 2 sorted linked lists. Given 2 sorted single linked lists -
first : 1-2-3-4-5-8-100-120
second : 5-7-11-34-109-130
Final : 1-2-3-4-5-5-7-8-34-100-109-120-130


Solution : The given problem can be solved by comparing each node of first list with second one and inserting nodes from second to first where ever there is a need. e.g. in the above example 5- in second node is inserted between 5-8 in first node.The code follows below :


The above problem can also be solved by simple merging as first-->next = second node and then sorting it,though sorting would be an expensive operation.In the next few articles we will see how sorting can be performed efficiently using linked lists.



Comments

  1. Your solution for MergeSort works great in most cases where the lists have more than two nodes in them. It breaks however, when the lists have less than two nodes. You might want to address them as special cases in your algorithm;

    ReplyDelete
  2. Hi,Nice solution for MergeSort of linked lists in c#.Iam interested in the above code.Its very useful for me to test the program.Thanks..

    -Aparna
    Theosoft

    ReplyDelete

Post a Comment

Popular posts from this blog

Simple linked list implementation in C#

Some basic linked list problems

Composition over Inheritance