Open In App

Merge two sorted linked lists using Dummy Nodes

Last Updated : 17 Aug, 2024
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 (in place) and return the head of the merged list.

Examples:

Input: a: 5->10->15, b: 2->3->20
Output: 2->3->5->10->15->20

Input: a: 1->1, b: 2->4
Output: 1->1->2->4

The idea is to use a temporary dummy node as the start of the result list. The pointer Tail always points to the last node in the result list, so appending new nodes is easy.Follow the below illustration for a better understanding:

Merge-Two-Sorted-LinkedLists1

Follow the steps below to solve the problem:

  • First, make a dummy node for the new merged linked list
  • Now make two pointers, one will point to list1 and another will point to list2.
  • Now traverse the lists till one of them gets exhausted.
  • If the value of the node pointing to either list is smaller than another pointer, add that node to our merged list and increment that pointer.

Below is the implementation of the above approach: 

C++
// C++ program to merge two sorted linked lists
// using dummy nodes
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node* next;
    Node(int new_data)
    {
        this->data = new_data;
        this->next = nullptr;
    }
};

// Function that takes two lists sorted in increasing order,
// and splices their nodes together to make one big sorted
// list which is returned.
Node* mergeSortedList(Node* first, Node* second) {
  
    // A dummy first node to hang the result on
    Node dummy(-1);

    // Tail points to the last result node
    Node* tail = &dummy;

    // So tail->next is the place to add new nodes to the
    // result
    while (1) {
        if (first == NULL) {
          
            // If either list runs out, use the other list
            tail->next = second;
            break;
        }
        else if (first == NULL) {
            tail->next = first;
            break;
        }
        if (first->data <= second->data) {
          
            // Move the front node from 'a' to the result
            // list
            Node* newNode = first;
            first = first->next;
            newNode->next = tail->next;
            tail->next = newNode;
        }
        else {
          
            // Move the front node from 'b' to the result
            // list
            Node* newNode = second;
            second = second->next;
            newNode->next = tail->next;
            tail->next = newNode;
        }

        tail = tail->next;
    }
    return (dummy.next);
}

// Driver code
int main() {
  
    // Create a hard-coded linked list:
    // 2 -> 4 -> 8 -> 9
    Node* first = new Node(2);
    first->next = new Node(4);
    first->next->next = new Node(8);
    first->next->next->next = new Node(9);

    // Create another hard-coded linked list:
    // 1 -> 3 -> 8 -> 10
    Node* second = new Node(1);
    second->next = new Node(3);
    second->next->next = new Node(8);
    second->next->next->next = new Node(10);

    Node* mergedList = mergeSortedList(first, second);

    Node* temp = mergedList;
  	cout << "Merged Link List is:" << endl;
    while (temp) {
        cout << temp->data << " ";
        temp = temp->next;
    }
    return 0;
}
C
// C program to merge two sorted linked lists
// using dummy nodes
#include <stdio.h>
#include <stdlib.h>

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

// Function that takes two lists sorted in increasing order,
// and splices their nodes together to make one big sorted
// list which is returned.
Node* mergeSortedList(Node* first, Node* second) {

    // A dummy first node to hang the result on
    Node dummy;
    dummy.data = -1;
    dummy.next = NULL;

    // Tail points to the last result node
    Node* tail = &dummy;

    // So tail->next is the place to add new nodes to the
    // result
    while (1) {
        if (first == NULL) {

            // If either list runs out, use the other list
            tail->next = second;
            break;
        }
        else if (second == NULL) {
            tail->next = first;
            break;
        }
        if (first->data <= second->data) {

            // Move the front node from 'first' to the
            // result list
            Node* newNode = first;
            first = first->next;
            newNode->next = tail->next;
            tail->next = newNode;
        }
        else {

            // Move the front node from 'second' to the
            // result list
            Node* newNode = second;
            second = second->next;
            newNode->next = tail->next;
            tail->next = newNode;
        }

        tail = tail->next;
    }
    return (dummy.next);
}

// Driver code
int main() {

    // Create a hard-coded linked list:
    // 2 -> 4 -> 8 -> 9
    Node* first = createNode(2);
    first->next = createNode(4);
    first->next->next = createNode(8);
    first->next->next->next = createNode(9);

    // Create another hard-coded linked list:
    // 1 -> 3 -> 8 -> 10
    Node* second = createNode(1);
    second->next = createNode(3);
    second->next->next = createNode(8);
    second->next->next->next = createNode(10);

    Node* mergedList = mergeSortedList(first, second);

    Node* temp = mergedList;
  	printf("Merged Link List is:\n");
    while (temp) {
        printf("%d ", temp->data);
        temp = temp->next;
    }
    return 0;
}
Java
// Java program to merge two sorted linked lists
// using dummy nodes
class Node {
    int data;
    Node next;
    Node(int new_data) {
        this.data = new_data;
        this.next = null;
    }
}

class GfG {

    // Function that takes two lists sorted in increasing
    // order, and splices their nodes together to make one
    // big sorted list which is returned.
    public static Node mergeSortedList(Node first,
                                       Node second) {

        // A dummy first node to hang the result on
        Node dummy = new Node(-1);

        // Tail points to the last result node
        Node tail = dummy;

        // So tail.next is the place to add new nodes to the
        // result
        while (true) {
            if (first == null) {

                // If either list runs out, use the other
                // list
                tail.next = second;
                break;
            }
            else if (second == null) {
                tail.next = first;
                break;
            }
            if (first.data <= second.data) {

                // Move the front node from 'first' to the
                // result list
                Node newNode = first;
                first = first.next;
                newNode.next = tail.next;
                tail.next = newNode;
            }
            else {

                // Move the front node from 'second' to the
                // result list
                Node newNode = second;
                second = second.next;
                newNode.next = tail.next;
                tail.next = newNode;
            }

            tail = tail.next;
        }
        return (dummy.next);
    }

    // Driver code
    public static void main(String[] args) {

        // Create a hard-coded linked list:
        // 2 -> 4 -> 8 -> 9
        Node first = new Node(2);
        first.next = new Node(4);
        first.next.next = new Node(8);
        first.next.next.next = new Node(9);

        // Create another hard-coded linked list:
        // 1 -> 3 -> 8 -> 10
        Node second = new Node(1);
        second.next = new Node(3);
        second.next.next = new Node(8);
        second.next.next.next = new Node(10);

        Node mergedList = mergeSortedList(first, second);

        Node temp = mergedList;
       	System.out.print("Merged Link List is:\n");
        while (temp != null) {
            System.out.print(temp.data + " ");
            temp = temp.next;
        }
    }
}
Python
# Python program to merge two sorted linked lists
# using dummy nodes

class Node:
    def __init__(self, new_data):
        self.data = new_data
        self.next = None

# Function that takes two lists sorted in increasing order,
# and splices their nodes together to make one big sorted
# list which is returned.
def merge_sorted_list(first, second):

    # A dummy first node to hang the result on
    dummy = Node(-1)

    # Tail points to the last result node
    tail = dummy

    # So tail.next is the place to add new nodes to the
    # result
    while True:
        if first is None:

            # If either list runs out, use the other list
            tail.next = second
            break
        elif second is None:
            tail.next = first
            break
        if first.data <= second.data:

            # Move the front node from 'first' to the result
            # list
            new_node = first
            first = first.next
            new_node.next = tail.next
            tail.next = new_node
        else:

            # Move the front node from 'second' to the result
            # list
            new_node = second
            second = second.next
            new_node.next = tail.next
            tail.next = new_node

        tail = tail.next
    return dummy.next

# Driver code

# Create a hard-coded linked list:
# 2 -> 4 -> 8 -> 9
first = Node(2)
first.next = Node(4)
first.next.next = Node(8)
first.next.next.next = Node(9)

# Create another hard-coded linked list:
# 1 -> 3 -> 8 -> 10
second = Node(1)
second.next = Node(3)
second.next.next = Node(8)
second.next.next.next = Node(10)

merged_list = merge_sorted_list(first, second)

temp = merged_list
print("Merged Link List is:")
while temp:
        print(temp.data, end=" ")
        temp = temp.next
C#
// C# program to merge two sorted linked lists
// using dummy nodes
using System;

class Node {
    public int data;
    public Node next;
    public Node(int new_data) {
        this.data = new_data;
        this.next = null;
    }
}

class GfG {
  
    // Function that takes two lists sorted in increasing
    // order, and splices their nodes together to make one
    // big sorted list which is returned.
    public static Node mergeSortedList(Node first,
                                       Node second) {

        // A dummy first node to hang the result on
        Node dummy = new Node(-1);

        // Tail points to the last result node
        Node tail = dummy;

        // So tail.next is the place to add new nodes to the
        // result
        while (true) {
            if (first == null) {

                // If either list runs out, use the other
                // list
                tail.next = second;
                break;
            }
            else if (second == null) {
                tail.next = first;
                break;
            }
            if (first.data <= second.data) {

                // Move the front node from 'first' to the
                // result list
                Node newNode = first;
                first = first.next;
                newNode.next = tail.next;
                tail.next = newNode;
            }
            else {

                // Move the front node from 'second' to the
                // result list
                Node newNode = second;
                second = second.next;
                newNode.next = tail.next;
                tail.next = newNode;
            }

            tail = tail.next;
        }
        return dummy.next;
    }

    // Driver code
    public static void Main(string[] args) {

        // Create a hard-coded linked list:
        // 2 -> 4 -> 8 -> 9
        Node first = new Node(2);
        first.next = new Node(4);
        first.next.next = new Node(8);
        first.next.next.next = new Node(9);

        // Create another hard-coded linked list:
        // 1 -> 3 -> 8 -> 10
        Node second = new Node(1);
        second.next = new Node(3);
        second.next.next = new Node(8);
        second.next.next.next = new Node(10);

        Node mergedList = mergeSortedList(first, second);

        Node temp = mergedList;
      	Console.Write("Merged Link List is:\n");
        while (temp != null) {
            Console.Write(temp.data + " ");
            temp = temp.next;
        }
    }
}
JavaScript
// JavaScript program to merge two sorted linked lists
// using dummy nodes
class Node {
    constructor(new_data) {
        this.data = new_data;
        this.next = null;
    }
}

class GfG {

    // Function that takes two lists sorted in increasing
    // order, and splices their nodes together to make one
    // big sorted list which is returned.
    static mergeSortedList(first, second) {

        // A dummy first node to hang the result on
        let dummy = new Node(-1);

        // Tail points to the last result node
        let tail = dummy;

        // So tail.next is the place to add new nodes to the
        // result
        while (true) {
            if (first === null) {

                // If either list runs out, use the other
                // list
                tail.next = second;
                break;
            }
            else if (second === null) {
                tail.next = first;
                break;
            }
            if (first.data <= second.data) {

                // Move the front node from 'first' to the
                // result list
                let newNode = first;
                first = first.next;
                newNode.next = tail.next;
                tail.next = newNode;
            }
            else {

                // Move the front node from 'second' to the
                // result list
                let newNode = second;
                second = second.next;
                newNode.next = tail.next;
                tail.next = newNode;
            }

            tail = tail.next;
        }
        return dummy.next;
    }
}

// Driver code

// Create a hard-coded linked list:
// 2 -> 4 -> 8 -> 9
let first = new Node(2);
first.next = new Node(4);
first.next.next = new Node(8);
first.next.next.next = new Node(9);

// Create another hard-coded linked list:
// 1 -> 3 -> 8 -> 10
let second = new Node(1);
second.next = new Node(3);
second.next.next = new Node(8);
second.next.next.next = new Node(10);

let mergedList = GfG.mergeSortedList(first, second);

let temp = mergedList;
process.stdout.write("Merged Link List is:\n");
while (temp !== null) {
    process.stdout.write(temp.data + " ");
    temp = temp.next;
}

Output
Merged Linked List is: 
2 3 5 10 15 20 

Time Complexity: O(N + M), where N and M are the size of list1 and list2 respectively
Auxiliary Space: O(1)

Merge Two Sorted Linked Lists
Merge Two Sorted Linked Lists with O(1) Auxiliary Space


Next Article
Article Tags :
Practice Tags :

Similar Reads