Given two sorted linked lists consisting of n and m nodes respectively. The task is to merge both of the lists and return the head of the merged list.
Example:
Input:
Output:
Input:
Output:
Approach:
The idea is to iteratively merge two sorted linked lists using a dummy node to simplify the process. A current pointer tracks the last node of the merged list. We compare the nodes from both lists and append the smaller node to the merged list. Once one list is fully traversed, the remaining nodes from the other list are appended. The merged list is returned starting from the node after the dummy node.
Below is the working of above approach:
Below is the implementation of above approach:
C++
// C++ program to merge two sorted linked// lists iteratively#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};// Function to merge two sorted linked// lists iterativelyNode*sortedMerge(Node*head1,Node*head2){// Create a dummy node to simplify // the merging processNode*dummy=newNode(-1);Node*curr=dummy;// Iterate through both linked listswhile(head1!=nullptr&&head2!=nullptr){// Add the smaller node to the merged listif(head1->data<=head2->data){curr->next=head1;head1=head1->next;}else{curr->next=head2;head2=head2->next;}curr=curr->next;}// If any list is left, append it to// the merged listif(head1!=nullptr){curr->next=head1;}else{curr->next=head2;}// Return the merged list starting// from the next of dummy nodereturndummy->next;}voidprintList(Node*head){while(head!=nullptr){cout<<head->data;if(head->next!=nullptr)cout<<" ";head=head->next;}cout<<endl;}intmain(){// First linked list: 5 -> 10 -> 15 -> 40Node*head1=newNode(5);head1->next=newNode(10);head1->next->next=newNode(15);head1->next->next->next=newNode(40);// Second linked list: 2 -> 3 -> 20Node*head2=newNode(2);head2->next=newNode(3);head2->next->next=newNode(20);Node*res=sortedMerge(head1,head2);printList(res);return0;}
C
// C program to merge two sorted linked // lists iteratively#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;};structNode*createNode(intdata);// Function to merge two sorted linked lists iterativelystructNode*sortedMerge(structNode*head1,structNode*head2){// Create a dummy node to simplify// the merging processstructNode*dummy=createNode(-1);structNode*curr=dummy;// Iterate through both linked listswhile(head1!=NULL&&head2!=NULL){// Add the smaller node to the merged listif(head1->data<=head2->data){curr->next=head1;head1=head1->next;}else{curr->next=head2;head2=head2->next;}curr=curr->next;}// If any list is left, append it to // the merged listif(head1!=NULL){curr->next=head1;}else{curr->next=head2;}// Return the merged list starting // from the next of dummy nodereturndummy->next;}// Function to print the linked listvoidprintList(structNode*head){while(head!=NULL){printf("%d",head->data);if(head->next!=NULL){printf(" ");}head=head->next;}printf("\n");}structNode*createNode(intdata){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=data;newNode->next=NULL;returnnewNode;}intmain(){// First linked list: 5 -> 10 -> 15 -> 40structNode*head1=createNode(5);head1->next=createNode(10);head1->next->next=createNode(15);head1->next->next->next=createNode(40);// Second linked list: 2 -> 3 -> 20structNode*head2=createNode(2);head2->next=createNode(3);head2->next->next=createNode(20);structNode*res=sortedMerge(head1,head2);printList(res);return0;}
Java
// Java program to merge two sorted linked // lists iterativelyclassNode{intdata;Nodenext;Node(intx){data=x;next=null;}}classGfG{// Function to merge two sorted linked // lists iterativelystaticNodesortedMerge(Nodehead1,Nodehead2){// Create a dummy node to simplify // the merging processNodedummy=newNode(-1);Nodecurr=dummy;// Iterate through both linked listswhile(head1!=null&&head2!=null){// Add the smaller node to the merged listif(head1.data<=head2.data){curr.next=head1;head1=head1.next;}else{curr.next=head2;head2=head2.next;}curr=curr.next;}// If any list is left, append it to // the merged listif(head1!=null){curr.next=head1;}else{curr.next=head2;}// Return the merged list starting from // the next of dummy nodereturndummy.next;}staticvoidprintList(Nodehead){while(head!=null){System.out.print(head.data);if(head.next!=null)System.out.print(" ");head=head.next;}System.out.println();}publicstaticvoidmain(String[]args){// First linked list: 5 -> 10 -> 15 -> 40Nodehead1=newNode(5);head1.next=newNode(10);head1.next.next=newNode(15);head1.next.next.next=newNode(40);// Second linked list: 2 -> 3 -> 20Nodehead2=newNode(2);head2.next=newNode(3);head2.next.next=newNode(20);Noderes=sortedMerge(head1,head2);printList(res);}}
Python
# Python program to merge two sorted linked # lists iterativelyclassNode:def__init__(self,x):self.data=xself.next=None# Function to merge two sorted linked # lists iterativelydefsortedMerge(head1,head2):# Create a dummy node to simplify # the merging processdummy=Node(-1)curr=dummy# Iterate through both linked listswhilehead1isnotNoneandhead2isnotNone:# Add the smaller node to the merged listifhead1.data<=head2.data:curr.next=head1head1=head1.nextelse:curr.next=head2head2=head2.nextcurr=curr.next# If any list is left, append it to the merged listifhead1isnotNone:curr.next=head1else:curr.next=head2# Return the merged list starting from # the next of dummy nodereturndummy.nextdefprintList(head):whileheadisnotNone:print(head.data,end=" ")head=head.nextprint()if__name__=="__main__":# First linked list: 5 -> 10 -> 15 -> 40head1=Node(5)head1.next=Node(10)head1.next.next=Node(15)head1.next.next.next=Node(40)# Second linked list: 2 -> 3 -> 20head2=Node(2)head2.next=Node(3)head2.next.next=Node(20)res=sortedMerge(head1,head2)printList(res)
C#
// C# program to merge two sorted linked // lists iterativelyusingSystem;classNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGfG{// Function to merge two sorted linked // lists iterativelystaticNodesortedMerge(Nodehead1,Nodehead2){// Create a dummy node to simplify the // merging processNodedummy=newNode(-1);Nodecurr=dummy;// Iterate through both linked listswhile(head1!=null&&head2!=null){// Add the smaller node to the merged listif(head1.data<=head2.data){curr.next=head1;head1=head1.next;}else{curr.next=head2;head2=head2.next;}curr=curr.next;}// If any list is left, append it to the // merged listif(head1!=null){curr.next=head1;}else{curr.next=head2;}// Return the merged list starting from // the next of dummy nodereturndummy.next;}staticvoidprintList(Nodehead){while(head!=null){Console.Write(head.data);if(head.next!=null)Console.Write(" ");head=head.next;}Console.WriteLine();}staticvoidMain(string[]args){// First linked list: 5 -> 10 -> 15 -> 40Nodehead1=newNode(5);head1.next=newNode(10);head1.next.next=newNode(15);head1.next.next.next=newNode(40);// Second linked list: 2 -> 3 -> 20Nodehead2=newNode(2);head2.next=newNode(3);head2.next.next=newNode(20);Noderes=sortedMerge(head1,head2);printList(res);}}
JavaScript
// JavaScript program to merge two sorted// linked lists iterativelyclassNode{constructor(x){this.data=x;this.next=null;}}// Function to merge two sorted linked lists iterativelyfunctionsortedMerge(head1,head2){// Create a dummy node to simplify the merging processletdummy=newNode(-1);letcurr=dummy;// Iterate through both linked listswhile(head1!==null&&head2!==null){// Add the smaller node to the merged listif(head1.data<=head2.data){curr.next=head1;head1=head1.next;}else{curr.next=head2;head2=head2.next;}curr=curr.next;}// If any list is left, append it// to the merged listif(head1!==null){curr.next=head1;}else{curr.next=head2;}// Return the merged list starting from// the next of dummy nodereturndummy.next;}functionprintList(head){letresult="";while(head!==null){result+=head.data;if(head.next!==null){result+=" ";}head=head.next;}console.log(result);}// driver code// First linked list: 5 -> 10 -> 15 -> 40lethead1=newNode(5);head1.next=newNode(10);head1.next.next=newNode(15);head1.next.next.next=newNode(40);// Second linked list: 2 -> 3 -> 20lethead2=newNode(2);head2.next=newNode(3);head2.next.next=newNode(20);letres=sortedMerge(head1,head2);printList(res);
Output
2 3 5 10 15 20 40
Time Complexity: O(n + m), where n and m are the length of head1 and head2 respectively. Auxiliary Space: O(1)
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.