Merge two sorted linked lists (original) (raw)

Last Updated : 23 Dec, 2024

Try it on GfG Practice redirect icon

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.

**Examples:

**Input:

1

**Output:

3

**Input:

1

**Output:

4

Table of Content

[Naive Approach] By Using Array - O((n+m)*log(n+m)) Time and O(n+m) Space

The idea is to merge two sorted linked lists into one sorted linked list. First, the elements from both linked lists are extracted and stored in an **array. This allows easy **sorting of the values. After sorting, a new linked list is created by sequentially inserting the sorted elements from the array. Finally, the merged sorted linked list is returned.

C++ `

// C++ program to merge two sorted linked lists // using array #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 Node *sortedMerge(Node *head1, Node *head2) { vector arr;

// Pushing the values of the first linked list
while (head1 != nullptr) {
    arr.push_back(head1->data);
    head1 = head1->next;
}

// Pushing the values of the second linked list
while (head2 != nullptr) {
    arr.push_back(head2->data);
    head2 = head2->next;
}

// Sorting the vector
sort(arr.begin(), arr.end());

// Creating a new list with sorted values
Node *dummy = new Node(-1);
Node *curr = dummy;

for (int i = 0; i < arr.size(); i++) {
    curr->next = new Node(arr[i]);
    curr = curr->next;
}

return dummy->next;

}

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

int main() {

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

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

// Merging the two sorted linked lists
Node *res = sortedMerge(head1, head2);

printList(res);

return 0;

}

Java

// Java program to merge two sorted linked lists // using array import java.util.*;

class Node { int data; Node next;

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

}

class GfG {

// Function to merge two sorted linked lists
static Node sortedMerge(Node head1,
                                   Node head2) {
    ArrayList<Integer> arr = new ArrayList<>();

    // Pushing the values of the first linked list
    while (head1 != null) {
        arr.add(head1.data);
        head1 = head1.next;
    }

    // Pushing the values of the second linked list
    while (head2 != null) {
        arr.add(head2.data);
        head2 = head2.next;
    }

    // Sorting the list
    Collections.sort(arr);

    // Creating a new list with sorted values
    Node dummy = new Node(-1);
    Node curr = dummy;

    for (int i = 0; i < arr.size(); i++) {
        curr.next = new Node(arr.get(i));
        curr = curr.next;
    }

    return dummy.next;
}

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

public static void main(String[] args) {

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

    // 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

using array

class Node: def init(self, x): self.data = x self.next = None

Function to merge two sorted linked lists

def sortedMerge(head1, head2): arr = []

# Pushing the values of the first linked list
while head1 is not None:
    arr.append(head1.data)
    head1 = head1.next

# Pushing the values of the second linked list
while head2 is not None:
    arr.append(head2.data)
    head2 = head2.next

# Sorting the list
arr.sort()

# Creating a new list with sorted values
dummy = Node(-1)
curr = dummy

for value in arr:
    curr.next = Node(value)
    curr = curr.next

return dummy.next 

Function to print the linked list

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

if name == "main":

# First linked list: 5 -> 10 -> 15
head1 = Node(5)
head1.next = Node(10)
head1.next.next = Node(15)

# 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 // using array using System; using System.Collections.Generic;

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
static Node sortedMerge(Node head1,
                                   Node head2) {
    List<int> arr = new List<int>();

    // Pushing the values of the first linked list
    while (head1 != null) {
        arr.Add(head1.data);
        head1 = head1.next;
    }

    // Pushing the values of the second linked list
    while (head2 != null) {
        arr.Add(head2.data);
        head2 = head2.next;
    }

    // Sorting the list
    arr.Sort();

    // Creating a new list with sorted values
    Node dummy = new Node(-1);
    Node curr = dummy;

    foreach(int value in arr) {
        curr.next = new Node(value);
        curr = curr.next;
    }

    return dummy.next;
}

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

static void Main(string[] args) {

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

    // 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 // using array

class Node { constructor(x) { this.data = x; this.next = null; } }

// Function to merge two sorted linked lists function sortedMerge(head1, head2) { let arr = [];

// Pushing the values of the first linked list
while (head1 !== null) {
    arr.push(head1.data);
    head1 = head1.next;
}

// Pushing the values of the second linked list
while (head2 !== null) {
    arr.push(head2.data);
    head2 = head2.next;
}

// Sorting the array
arr.sort((x, y) => x - y);

// Creating a new list with sorted values
let dummy = new Node(-1);
let curr = dummy;

for (let value of arr) {
    curr.next = new Node(value);
    curr = curr.next;
}

return dummy.next;

}

function printList(curr) { let result = ""; while (curr !== null) { result += curr.data.toString(); if (curr.next !== null) { result += " "; } curr = curr.next; } console.log(result); }

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

// 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);

`

**[Better Approach] **Using Recursive Merge - O(n+m) Time and O(n+m) Space

The idea is to merge two sorted linked lists using recursion. The base cases handle the scenarios where one of the lists is empty, in which case the other list is returned directly. In the recursive step, the function compares the data of the current nodes of both lists and attaches the smaller node to the merged list. The function then recursively merges the remaining part of the list. This process continues until both lists are fully merged. This approach eliminates the need for extra space and efficiently merges the lists.

C++ `

// C++ program to merge two sorted linked // lists recursively #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 recursively Node* sortedMerge(Node* head1, Node* head2) {

// Base cases
if (head1 == nullptr) 
    return head2;
if (head2 == nullptr) 
    return head1;

// Recursive merging based on smaller value
if (head1->data <= head2->data) {
    head1->next = sortedMerge(head1->next, head2);
    return head1;
} else {
    head2->next = sortedMerge(head1, head2->next);
    return head2;
}

}

// Function to print the linked list void printList(Node* curr) { while (curr != nullptr) { cout << curr->data; if (curr->next != nullptr) cout << " "; curr = curr->next; } cout << endl; }

int main() {

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

// 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 recursively #include <stdio.h> #include <stdlib.h>

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

// Function to merge two sorted linked lists recursively struct Node *sortedMerge(struct Node *head1, struct Node *head2) {

// Base cases
if (head1 == NULL)
    return head2;
if (head2 == NULL)
    return head1;

// Recursive merging based on smaller value
if (head1->data <= head2->data) {
    head1->next = sortedMerge(head1->next, head2);
    return head1;
}
else {
    head2->next = sortedMerge(head1, head2->next);
    return head2;
}

}

// Function to print the linked list void printList(struct Node *curr) { while (curr != NULL) { printf("%d", curr->data); if (curr->next != NULL) { printf(" "); } curr = curr->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
struct Node *head1 = createNode(5);
head1->next = createNode(10);
head1->next->next = createNode(15);

// 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 recursively class Node { int data; Node next;

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

}

class GfG {

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

    // Base cases
    if (head1 == null)
        return head2;
    if (head2 == null)
        return head1;

    // Recursive merging based on smaller value
    if (head1.data <= head2.data) {
        head1.next = sortedMerge(head1.next, head2);
        return head1;
    }
    else {
        head2.next = sortedMerge(head1, head2.next);
        return head2;
    }
}

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

public static void main(String[] args) {

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

    // 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 recursively

class Node: def init(self, x): self.data = x self.next = None

Function to merge two sorted linked lists recursively

def sortedMerge(head1, head2):

# Base cases
if head1 is None:
    return head2
if head2 is None:
    return head1

# Recursive merging based on smaller value
if head1.data <= head2.data:
    head1.next = sortedMerge(head1.next, head2)
    return head1
else:
    head2.next = sortedMerge(head1, head2.next)
    return head2

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

if name == "main":

# First linked list: 5 -> 10 -> 15
head1 = Node(5)
head1.next = Node(10)
head1.next.next = Node(15)

# 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 recursively 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 recursively
static Node sortedMerge(Node head1,
                                   Node head2) {

    // Base cases
    if (head1 == null)
        return head2;
    if (head2 == null)
        return head1;

    // Recursive merging based on smaller value
    if (head1.data <= head2.data) {
        head1.next = sortedMerge(head1.next, head2);
        return head1;
    }
    else {
        head2.next = sortedMerge(head1, head2.next);
        return head2;
    }
}

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

static void Main(string[] args) {

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

    // 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 recursively class Node { constructor(x) { this.data = x; this.next = null; } }

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

// Base cases
if (head1 === null)
    return head2;
if (head2 === null)
    return head1;

// Recursive merging based on smaller value
if (head1.data <= head2.data) {
    head1.next = sortedMerge(head1.next, head2);
    return head1;
}
else {
    head2.next = sortedMerge(head1, head2.next);
    return head2;
}

}

function printList(curr) { let result = ""; while (curr !== null) { result += curr.data.toString(); if (curr.next !== null) { result += " "; } curr = curr.next; } console.log(result); }

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

// 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);

`

**[Efficient Approach] **Using Iterative Merge - O(n+m) Time and O(1) Space

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. Please refer to Merge two sorted lists with O(1) auxiliary space.