Open In App

Merge two sorted lists (in-place)

Last Updated : 02 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

1


Output:

3


Input:

1


Output:

4

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>
using namespace std;

class Node {
public:
    int data;
    Node* next;

    Node(int x) {
        data = x;
        next = nullptr;
    }
};

// Function to merge two sorted linked
// lists iteratively
Node* sortedMerge(Node* head1, Node* head2) {
  
    // Create a dummy node to simplify 
    // the merging process
    Node* dummy = new Node(-1);
    Node* curr = dummy;

    // Iterate through both linked lists
    while (head1 != nullptr && head2 != nullptr) {
      
        // Add the smaller node to the merged list
        if (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 list
    if (head1 != nullptr) {
        curr->next = head1;
    } else {
        curr->next = head2;
    }

    // Return the merged list starting
    // from the next of dummy node
    return dummy->next;
}

void printList(Node* head) {
  
    while (head != nullptr) {
        cout << head->data;
        if (head->next != nullptr)
            cout << " ";
        head = head->next;
    }
    cout << endl;
}

int main() {
  
    // First linked list: 5 -> 10 -> 15 -> 40
    Node* head1 = new Node(5);
    head1->next = new Node(10);
    head1->next->next = new Node(15);
    head1->next->next->next = new Node(40);

    // Second linked list: 2 -> 3 -> 20
    Node* head2 = new Node(2);
    head2->next = new Node(3);
    head2->next->next = new Node(20);

    Node* res = sortedMerge(head1, head2);
    printList(res);

    return 0;
}
C
// C program to merge two sorted linked 
// lists iteratively
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* next;
};


struct Node* createNode(int data);

// Function to merge two sorted linked lists iteratively
struct Node* sortedMerge(struct Node* head1,
                             struct Node* head2) {
  
    // Create a dummy node to simplify
    // the merging process
    struct Node* dummy = createNode(-1);
    struct Node* curr = dummy;

    // Iterate through both linked lists
    while (head1 != NULL && head2 != NULL) {
      
        // Add the smaller node to the merged list
        if (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 list
    if (head1 != NULL) {
        curr->next = head1;
    } else {
        curr->next = head2;
    }

    // Return the merged list starting 
    // from the next of dummy node
    return dummy->next;
}

// Function to print the linked list
void printList(struct Node* head) {
    while (head != NULL) {
        printf("%d", head->data);
        if (head->next != NULL) {
            printf(" ");
        }
        head = head->next;
    }
    printf("\n");
}

struct Node* createNode(int data) {
    struct Node* newNode
      = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

int main() {
  
    // First linked list: 5 -> 10 -> 15 -> 40
    struct Node* head1 = createNode(5);
    head1->next = createNode(10);
    head1->next->next = createNode(15);
    head1->next->next->next = createNode(40);

    // Second linked list: 2 -> 3 -> 20
    struct Node* head2 = createNode(2);
    head2->next = createNode(3);
    head2->next->next = createNode(20);

    struct Node* res = sortedMerge(head1, head2);

    printList(res);

    return 0;
}
Java
// Java program to merge two sorted linked 
// lists iteratively
class Node {
    int data;
    Node next;

    Node(int x) {
        data = x;
        next = null;
    }
}

class GfG {

    // Function to merge two sorted linked 
    // lists iteratively
    static Node sortedMerge(Node head1,
                                       Node head2) {

        // Create a dummy node to simplify 
        // the merging process
        Node dummy = new Node(-1);
        Node curr = dummy;

        // Iterate through both linked lists
        while (head1 != null && head2 != null) {
          
            // Add the smaller node to the merged list
            if (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 list
        if (head1 != null) {
            curr.next = head1;
        } else {
            curr.next = head2;
        }

        // Return the merged list starting from 
        // the next of dummy node
        return dummy.next;
    }

    static void printList(Node head) {
        while (head != null) {
            System.out.print(head.data);
            if (head.next != null)
                System.out.print(" ");
            head = head.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {

        // First linked list: 5 -> 10 -> 15 -> 40
        Node head1 = new Node(5);
        head1.next = new Node(10);
        head1.next.next = new Node(15);
        head1.next.next.next = new Node(40);

        // Second linked list: 2 -> 3 -> 20
        Node head2 = new Node(2);
        head2.next = new Node(3);
        head2.next.next = new Node(20);

        Node res = sortedMerge(head1, head2);
        printList(res);
    }
}
Python
# Python program to merge two sorted linked 
# lists iteratively
class Node:
    def __init__(self, x):
        self.data = x
        self.next = None

# Function to merge two sorted linked 
# lists iteratively
def sortedMerge(head1, head2):
  
    # Create a dummy node to simplify 
    # the merging process
    dummy = Node(-1)
    curr = dummy

    # Iterate through both linked lists
    while head1 is not None and head2 is not None:
      
        # Add the smaller node to the merged list
        if 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 list
    if head1 is not None:
        curr.next = head1
    else:
        curr.next = head2

    # Return the merged list starting from 
    # the next of dummy node
    return dummy.next

def printList(head):
    while head is not None:
        print(head.data, end=" ")
        head = head.next
    print()

if __name__ == "__main__":
  
    # First linked list: 5 -> 10 -> 15 -> 40
    head1 = Node(5)
    head1.next = Node(10)
    head1.next.next = Node(15)
    head1.next.next.next = Node(40)

    # Second linked list: 2 -> 3 -> 20
    head2 = 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 iteratively
using System;

class Node {
    public int data;
    public Node next;

    public Node(int x) {
        data = x;
        next = null;
    }
}

class GfG {

    // Function to merge two sorted linked 
    // lists iteratively
    static Node sortedMerge(Node head1, Node head2) {
      
        // Create a dummy node to simplify the 
        // merging process
        Node dummy = new Node(-1);
        Node curr = dummy;

        // Iterate through both linked lists
        while (head1 != null && head2 != null) {
          
            // Add the smaller node to the merged list
            if (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 list
        if (head1 != null) {
            curr.next = head1;
        } else {
            curr.next = head2;
        }

        // Return the merged list starting from 
        // the next of dummy node
        return dummy.next;
    }

    static void printList(Node head) {
        while (head != null) {
            Console.Write(head.data);
            if (head.next != null)
                Console.Write(" ");
            head = head.next;
        }
        Console.WriteLine();
    }

    static void Main(string[] args) {
      
        // First linked list: 5 -> 10 -> 15 -> 40
        Node head1 = new Node(5);
        head1.next = new Node(10);
        head1.next.next = new Node(15);
        head1.next.next.next = new Node(40);

        // Second linked list: 2 -> 3 -> 20
        Node head2 = new Node(2);
        head2.next = new Node(3);
        head2.next.next = new Node(20);

        Node res = sortedMerge(head1, head2);
        printList(res);
    }
}
JavaScript
// JavaScript program to merge two sorted
// linked lists iteratively
class Node {
    constructor(x) {
        this.data = x;
        this.next = null;
    }
}

// Function to merge two sorted linked lists iteratively
function sortedMerge(head1, head2) {

    // Create a dummy node to simplify the merging process
    let dummy = new Node(-1);
    let curr = dummy;

    // Iterate through both linked lists
    while (head1 !== null && head2 !== null) {

        // Add the smaller node to the merged list
        if (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 list
    if (head1 !== null) {
        curr.next = head1;
    }
    else {
        curr.next = head2;
    }

    // Return the merged list starting from
    // the next of dummy node
    return dummy.next;
}

function printList(head) {
    let result = "";
    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 -> 40
let head1 = new Node(5);
head1.next = new Node(10);
head1.next.next = new Node(15);
head1.next.next.next = new Node(40);

// Second linked list: 2 -> 3 -> 20
let head2 = new Node(2);
head2.next = new Node(3);
head2.next.next = new Node(20);

let res = 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)

Related article:


Next Article

Similar Reads