Ticker

20/recent/ticker-posts

In this article let's learn how to merge two sorted linked lists in an efficient and easy manner. This problem is a part of data structures(Linked Lists). This problem was frequently asked in big tech company interviews, so now let's get into the problem and its optimized solution.

Now let's see what a linked list is and how it works along with its advantages.

• The linked list is a data structure that stores a linear collection of data elements, called nodes which are stored in memory at random locations.
• In the linked list, each node is divided into two parts.
• The first part contains the data of the element.
• The second part contains the address of the next node in the list.

• A linked list is a dynamic data structure, so it is easy to allocate and deallocate memory.
• No memory wastage.
• Insertion and deletion of elements are easier.
• Using a linked list one can implement sack and queue.

The problem is you will be given with two linked lists which are in sorted order, we have to merge these two linked lists into a fully sorted linked list.

Output:- 1->2->3->4->5->6->7->8

Lets focus on the function mergelists():
• Function mergelists() has two parameters h1 and h2.
• h1 is a reference to the head of linked list 1.
• h2 is a reference to the head of linked list 2.
• Take a dummy node(temp) and initialize NULL to it.
• Now run a loop and compare the node values of both the linked lists.
• If the node value of one linked list is less than the node value of the other then assign the lesser node value to the temp node.
• Repeat these steps until any of the lists reached its end.
• Then merge the remaining nodes to the temp so that the output will be fully merged sorted linked list.
Program to merge two sorted linked lists-CPP

#include<iostream>
using namespace std;
class node{
public:
int data;
node *next;
};
void push(node **head,int val)  //nodes are inserted at the front
{
node *new_node=new node();
new_node->data=val;
}
{
{
}
}
node *mergelists(node *h1,node *h2)
{
node *temp=new node();
temp->data=0;
while(h1!=NULL && h2!=NULL)
{
if(h1->data < h2->data)
{
temp->next=h1;
h1=h1->next;
}
else{
temp->next=h2;
h2=h2->next;
}
temp=temp->next;
}
if(h1!=NULL)
{
temp->next=h1;
}
else{
temp->next=h2;
}
}
int main()
{