Merge K sorted linked lists

Last Updated : 20 Oct, 2026

Given k sorted linked lists of different sizes, we need to merge them into a single list while maintaining their sorted order.

Examples: 

Input:

Input-1


Output:

Output-1

Explanation: Merged lists in a sorted order where every element is greater than the previous element.

Input:

Input-2


Output:

Output2
Try It Yourself
redirect icon

[Naive Approach] Repeatedly Select the Min - O(n*k) Time and O(1) Space

The idea is to iterate through all the k head nodes and do the following until all nodes are processed.

  • Append the head node with minimum value to the resultant list.
  • Increment the head to next node.

Step by step approach:

  • Initialize a dummy head for the resultant list.
  • Find the node with the smallest value in all the k lists.
  • Increment the current pointer to the next node of the list where the smallest node is found.
  • Append the node with smallest value to the resultant list.
  • Repeat these steps till all nodes have been used.
C++
#include <iostream>
#include <vector>
using namespace std;

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

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

Node *mergeKLists(vector<Node *> &arr)
{
    Node dummy(0);
    Node *tail = &dummy;

    while (true)
    {
        int minIndex = -1;

        // Find the minimum current node
        for (int i = 0; i < arr.size(); i++)
        {
            if (arr[i] != nullptr && (minIndex == -1 || arr[i]->data < arr[minIndex]->data))
            {
                minIndex = i;
            }
        }

        if (minIndex == -1)
            break;

        tail->next = arr[minIndex];
        tail = tail->next;

        arr[minIndex] = arr[minIndex]->next;
    }

    return dummy.next;
}

int main()
{
    vector<vector<int>> lists = {{1, 4, 7}, {2, 8}, {3, 9}};
    vector<Node *> arr;

    // Convert each array into a linked list
    for (const auto &row : lists)
    {
        Node *head = nullptr;
        Node *temp = nullptr;

        for (int x : row)
        {
            Node *newNode = new Node(x);

            if (head == nullptr)
            {
                head = newNode;
                temp = newNode;
            }
            else
            {
                temp->next = newNode;
                temp = temp->next;
            }
        }

        arr.push_back(head);
    }

    Node *res = mergeKLists(arr);

    // Print the merged linked list
    while (res != nullptr)
    {
        cout << res->data;

        if (res->next != nullptr)
            cout << " -> ";

        res = res->next;
    }

    cout << "\n";

    return 0;
}
Java
import java.util.*;

class Node {
    int data;
    Node next;

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

class GFG {
    static Node mergeKLists(Node[] arr)
    {
        Node dummy = new Node(0);
        Node tail = dummy;

        while (true) {
            int minIndex = -1;

            // Find the minimum current node
            for (int i = 0; i < arr.length; i++) {
                if (arr[i] != null
                    && (minIndex == -1
                        || arr[i].data
                               < arr[minIndex].data)) {
                    minIndex = i;
                }
            }

            if (minIndex == -1)
                break;

            tail.next = arr[minIndex];
            tail = tail.next;

            arr[minIndex] = arr[minIndex].next;
        }

        return dummy.next;
    }

    public static void main(String[] args)
    {
        int[][] lists = { { 1, 4, 7 }, { 2, 8 }, { 3, 9 } };
        Node[] arr = new Node[lists.length];

        // Convert each array into a linked list
        for (int i = 0; i < lists.length; i++) {
            Node head = null;
            Node temp = null;

            for (int x : lists[i]) {
                Node newNode = new Node(x);

                if (head == null) {
                    head = newNode;
                    temp = newNode;
                }
                else {
                    temp.next = newNode;
                    temp = temp.next;
                }
            }

            arr[i] = head;
        }

        Node res = mergeKLists(arr);

        // Print the merged linked list
        while (res != null) {
            System.out.print(res.data);

            if (res.next != null)
                System.out.print(" -> ");

            res = res.next;
        }

        System.out.println();
    }
}
Python
class Node:
    def __init__(self, x):
        self.data = x
        self.next = None


def mergeKLists(arr):
    dummy = Node(0)
    tail = dummy

    while True:
        min_index = -1

        # Find the minimum current node
        for i in range(len(arr)):
            if arr[i] is not None and (
                min_index == -1 or
                arr[i].data < arr[min_index].data
            ):
                min_index = i

        if min_index == -1:
            break

        tail.next = arr[min_index]
        tail = tail.next

        arr[min_index] = arr[min_index].next

    return dummy.next


# Driver Code
if __name__ == "__main__":
    lists = [
        [1, 4, 7],
        [2, 8],
        [3, 9]
    ]

    arr = []

    # Convert each array into a linked list
    for row in lists:
        head = None
        temp = None

        for x in row:
            new_node = Node(x)

            if head is None:
                head = new_node
                temp = new_node
            else:
                temp.next = new_node
                temp = temp.next

        arr.append(head)

    res = mergeKLists(arr)

    # Print the merged linked list
    while res is not None:
        print(res.data, end="")

        if res.next is not None:
            print(" -> ", end="")

        res = res.next

    print()
C#
using System;

class Node {
    public int data;
    public Node next;

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

class GFG {
    static Node mergeKLists(Node[] arr)
    {
        Node dummy = new Node(0);
        Node tail = dummy;

        while (true) {
            int minIndex = -1;

            // Find the minimum current node
            for (int i = 0; i < arr.Length; i++) {
                if (arr[i] != null
                    && (minIndex == -1
                        || arr[i].data
                               < arr[minIndex].data)) {
                    minIndex = i;
                }
            }

            if (minIndex == -1)
                break;

            tail.next = arr[minIndex];
            tail = tail.next;

            arr[minIndex] = arr[minIndex].next;
        }

        return dummy.next;
    }

    public static void Main()
    {
        int[][] lists
            = { new int[] { 1, 4, 7 }, new int[] { 2, 8 },
                new int[] { 3, 9 } };

        Node[] arr = new Node[lists.Length];

        // Convert each array into a linked list
        for (int i = 0; i < lists.Length; i++) {
            Node head = null;
            Node temp = null;

            foreach(int x in lists[i])
            {
                Node newNode = new Node(x);

                if (head == null) {
                    head = newNode;
                    temp = newNode;
                }
                else {
                    temp.next = newNode;
                    temp = temp.next;
                }
            }

            arr[i] = head;
        }

        Node res = mergeKLists(arr);

        // Print the merged linked list
        while (res != null) {
            Console.Write(res.data);

            if (res.next != null)
                Console.Write(" -> ");

            res = res.next;
        }

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

function mergeKLists(arr)
{
    let dummy = new Node(0);
    let tail = dummy;

    while (true) {
        let minIndex = -1;

        // Find the minimum current node
        for (let i = 0; i < arr.length; i++) {
            if (arr[i] !== null
                && (minIndex === -1
                    || arr[i].data < arr[minIndex].data)) {
                minIndex = i;
            }
        }

        if (minIndex === -1)
            break;

        tail.next = arr[minIndex];
        tail = tail.next;

        arr[minIndex] = arr[minIndex].next;
    }

    return dummy.next;
}

// Driver code
let lists = [ [ 1, 4, 7 ], [ 2, 8 ], [ 3, 9 ] ];
let arr = [];

// Convert each array into a linked list
for (let row of lists) {
    let head = null;
    let temp = null;

    for (let x of row) {
        let newNode = new Node(x);

        if (head === null) {
            head = newNode;
            temp = newNode;
        }
        else {
            temp.next = newNode;
            temp = temp.next;
        }
    }

    arr.push(head);
}

let res = mergeKLists(arr);

let output = "";

while (res !== null) {
    output += res.data;

    if (res.next !== null)
        output += " -> ";

    res = res.next;
}

console.log(output);

Output
1 -> 2 -> 3 -> 4 -> 7 -> 8 -> 9

[Expected Approach - 1] Min Heap - O(n * log k) Time and O(k) Space

This solution is mainly an optimization over the previous approach. Instead of linearly traversing the array to find the minimum, we use min heap data structure and reduce the time complexity of this operation to O(log k).

This one works better for unequal sized lists.

Step by step approach:

  • Insert the head node of each non-empty linked list into the min-heap.
  • Extract the node with the smallest value from the min-heap.
  • Append the extracted node to the resultant list.
  • If the extracted node has a next node, insert that next node into the min-heap.
  • Repeat steps 2–4 until the min-heap becomes empty, then return dummy->next.
C++
#include <bits/stdc++.h>
using namespace std;

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

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

Node *mergeKLists(vector<Node *> &arr)
{
    // Define the comparator inside the function
    auto compare = [](Node *a, Node *b) { return a->data > b->data; };

    priority_queue<Node *, vector<Node *>, decltype(compare)> pq(compare);

    // Insert the head nodes of k lists
    for (Node *head : arr)
    {
        if (head != nullptr)
            pq.push(head);
    }

    // Initialize a dummy head
    Node dummy(-1);
    Node *tail = &dummy;

    while (!pq.empty())
    {

        // Pop the minimum node
        Node *top = pq.top();
        pq.pop();

        // Append the node to the merged list
        tail->next = top;
        tail = top;

        // Insert the next node from the same list
        if (top->next != nullptr)
            pq.push(top->next);
    }

    // Terminate the merged list
    tail->next = nullptr;

    return dummy.next;
}

int main()
{
    vector<vector<int>> lists = {{1, 4, 7}, {2, 8}, {3, 9}};
    vector<Node *> arr;

    // Convert arrays into linked lists
    for (const auto &row : lists)
    {
        Node *head = nullptr;
        Node *temp = nullptr;

        for (int x : row)
        {
            Node *newNode = new Node(x);

            if (head == nullptr)
            {
                head = newNode;
                temp = newNode;
            }
            else
            {
                temp->next = newNode;
                temp = temp->next;
            }
        }

        arr.push_back(head);
    }

    // Merge the k sorted linked lists
    Node *res = mergeKLists(arr);

    // Print the merged list
    while (res != nullptr)
    {
        cout << res->data;
        if (res->next != nullptr)
            cout << " -> ";
        res = res->next;
    }

    cout << '\n';

    return 0;
}
Java
import java.util.*;

class Node {
    int data;
    Node next;

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

class GFG {
    static Node mergeKLists(Node[] arr)
    {
        // Define the comparator inside the function
        PriorityQueue<Node> pq = new PriorityQueue<>(
            (a, b) -> Integer.compare(a.data, b.data));

        // Insert the head nodes of k lists
        for (Node head : arr) {
            if (head != null)
                pq.add(head);
        }

        // Initialize a dummy head
        Node dummy = new Node(-1);
        Node tail = dummy;

        while (!pq.isEmpty()) {

            // Pop the minimum node
            Node top = pq.poll();

            // Append the node to the merged list
            tail.next = top;
            tail = top;

            // Insert the next node from the same list
            if (top.next != null)
                pq.add(top.next);
        }

        // Terminate the merged list
        tail.next = null;

        return dummy.next;
    }

    public static void main(String[] args)
    {
        int[][] lists = { { 1, 4, 7 }, { 2, 8 }, { 3, 9 } };
        Node[] arr = new Node[lists.length];

        // Convert arrays into linked lists
        for (int i = 0; i < lists.length; i++) {
            Node head = null;
            Node temp = null;

            for (int x : lists[i]) {
                Node newNode = new Node(x);

                if (head == null) {
                    head = newNode;
                    temp = newNode;
                }
                else {
                    temp.next = newNode;
                    temp = temp.next;
                }
            }

            arr[i] = head;
        }

        // Merge the k sorted linked lists
        Node res = mergeKLists(arr);

        // Print the merged list
        while (res != null) {
            System.out.print(res.data);
            if (res.next != null)
                System.out.print(" -> ");
            res = res.next;
        }

        System.out.println();
    }
}
Python
import heapq

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


def mergeKLists(arr):
    pq = []

    # Insert the head nodes of all lists
    for i in range(len(arr)):
        head = arr[i]
        if head is not None:
            heapq.heappush(pq, (head.data, i, head))

    # Dummy node for the merged list
    dummy = Node(-1)
    tail = dummy

    while pq:
        _, index, top = heapq.heappop(pq)

        # Add node to merged list
        tail.next = top
        tail = top

        # Add next node of the current list
        if top.next is not None:
            heapq.heappush(pq, (top.next.data, index, top.next))

    # Terminate the merged list
    tail.next = None

    return dummy.next


def main():
    lists = [[1, 4, 7], [2, 8], [3, 9]]
    arr = []

    # Convert arrays into linked lists
    for row in lists:
        head = None
        temp = None

        for x in row:
            newNode = Node(x)

            if head is None:
                head = newNode
                temp = newNode
            else:
                temp.next = newNode
                temp = temp.next

        arr.append(head)

    # Merge the k sorted linked lists
    res = mergeKLists(arr)

    # Print the merged list
    while res is not None:
        print(res.data, end="")
        if res.next is not None:
            print(" -> ", end="")
        res = res.next

    print()

# Driver Code
if __name__ == "__main__":
    main()
C#
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node next;

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

class GFG {
    static Node mergeKLists(Node[] arr)
    {
        // Define the comparator inside the function
        PriorityQueue<Node, int> pq
            = new PriorityQueue<Node, int>();

        // Insert the head nodes of k lists
        foreach(Node head in arr)
        {
            if (head != null)
                pq.Enqueue(head, head.data);
        }

        // Initialize a dummy head
        Node dummy = new Node(-1);
        Node tail = dummy;

        while (pq.Count > 0) {
            // Pop the minimum node
            Node top = pq.Dequeue();

            // Append the node to the merged list
            tail.next = top;
            tail = top;

            // Insert the next node from the same list
            if (top.next != null)
                pq.Enqueue(top.next, top.next.data);
        }

        // Terminate the merged list
        tail.next = null;

        return dummy.next;
    }

    static void Main()
    {
        int[][] lists
            = { new int[] { 1, 4, 7 }, new int[] { 2, 8 },
                new int[] { 3, 9 } };

        Node[] arr = new Node[lists.Length];

        // Convert arrays into linked lists
        for (int i = 0; i < lists.Length; i++) {
            Node head = null;
            Node temp = null;

            foreach(int x in lists[i])
            {
                Node newNode = new Node(x);

                if (head == null) {
                    head = newNode;
                    temp = newNode;
                }
                else {
                    temp.next = newNode;
                    temp = temp.next;
                }
            }

            arr[i] = head;
        }

        // Merge the k sorted linked lists
        Node res = mergeKLists(arr);

        // Print the merged list
        while (res != null) {
            Console.Write(res.data);
            if (res.next != null)
                Console.Write(" -> ");
            res = res.next;
        }

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

class PriorityQueue {
    constructor(compare)
    {
        this.heap = [];
        this.compare = compare;
    }

    enqueue(value)
    {
        this.heap.push(value);
        this.bubbleUp();
    }

    bubbleUp()
    {
        let index = this.heap.length - 1;

        while (index > 0) {
            let parentIndex = Math.floor((index - 1) / 2);
            let element = this.heap[index];
            let parent = this.heap[parentIndex];

            if (this.compare(element, parent) >= 0)
                break;

            this.heap[index] = parent;
            this.heap[parentIndex] = element;
            index = parentIndex;
        }
    }

    dequeue()
    {
        let top = this.heap[0];
        let end = this.heap.pop();

        if (this.heap.length > 0) {
            this.heap[0] = end;
            this.sinkDown(0);
        }

        return top;
    }

    sinkDown(index)
    {
        let left = 2 * index + 1;
        let right = 2 * index + 2;
        let smallest = index;

        if (left < this.heap.length
            && this.compare(this.heap[left],
                            this.heap[smallest])
                   < 0) {
            smallest = left;
        }

        if (right < this.heap.length
            && this.compare(this.heap[right],
                            this.heap[smallest])
                   < 0) {
            smallest = right;
        }

        if (smallest !== index) {
            [this.heap[index], this.heap[smallest]] =
                [ this.heap[smallest], this.heap[index] ];

            this.sinkDown(smallest);
        }
    }

    isEmpty() { return this.heap.length === 0; }
}

function mergeKLists(arr)
{
    // Define the comparator inside the function
    const compare = (a, b) => a.data - b.data;
    const pq = new PriorityQueue(compare);

    // Insert the head nodes of k lists
    for (let head of arr) {
        if (head !== null)
            pq.enqueue(head);
    }

    // Initialize a dummy head
    let dummy = new Node(-1);
    let tail = dummy;

    while (!pq.isEmpty()) {

        // Pop the minimum node
        let top = pq.dequeue();

        // Append the node to the merged list
        tail.next = top;
        tail = top;

        // Insert the next node from the same list
        if (top.next !== null)
            pq.enqueue(top.next);
    }

    // Terminate the merged list
    tail.next = null;

    return dummy.next;
}


// Driver Code
function main()
{
    const lists = [ [ 1, 4, 7 ], [ 2, 8 ], [ 3, 9 ] ];
    const arr = [];

    // Convert arrays into linked lists
    for (const row of lists) {
        let head = null;
        let temp = null;

        for (const x of row) {
            const newNode = new Node(x);

            if (head === null) {
                head = newNode;
                temp = newNode;
            }
            else {
                temp.next = newNode;
                temp = temp.next;
            }
        }

        arr.push(head);
    }

    // Merge the k sorted linked lists
    let res = mergeKLists(arr);

    // Print the merged list
    let output = [];

    while (res !== null) {
        output.push(res.data);
        res = res.next;
    }

    console.log(output.join(" -> "));
}

main();

Output
1 -> 2 -> 3 -> 4 -> 7 -> 8 -> 9

[Expected Approach - 2] Divide and Conquer - O(n * log k) Time and O(log k) Space

The idea is to use divide and conquer algorithm.

  • Recursively split the k lists into two halves until we have pairs of lists to merge.
  • Then merge these pairs using a two-way merge procedure (similar to merge sort's merge step), and continue this process back up through the recursion tree until all lists are merged into a single sorted list.
  • This one works better for equal sized lists.

Step by step approach:

  • Split k lists into two parts: lists[0...mid] and lists[mid+1...end].
  • Recursively merge the left half of lists to get first sorted list.
  • Recursively merge the right half of lists to get second sorted list.
  • Merge the above two sorted lists using two-pointer approach.
  • Return the final merged sorted list.
C++
#include <bits/stdc++.h>
using namespace std;

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

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

Node *mergeTwoLists(Node *a, Node *b)
{
    Node dummy(-1);
    Node *tail = &dummy;

    // Merge both lists by selecting the smaller node
    while (a != nullptr && b != nullptr)
    {
        if (a->data <= b->data)
        {
            tail->next = a;
            a = a->next;
        }
        else
        {
            tail->next = b;
            b = b->next;
        }

        tail = tail->next;
    }

    // Attach the remaining nodes
    if (a != nullptr)
        tail->next = a;
    else
        tail->next = b;

    return dummy.next;
}

Node *mergeRange(vector<Node *> &arr, int left, int right)
{
    // If the range is empty
    if (left > right)
        return nullptr;

    // If only one list remains
    if (left == right)
        return arr[left];

    // Divide the range into two halves
    int mid = left + (right - left) / 2;

    Node *first = mergeRange(arr, left, mid);
    Node *second = mergeRange(arr, mid + 1, right);

    // Merge the results of both halves
    return mergeTwoLists(first, second);
}

Node *mergeKLists(vector<Node *> &arr)
{
    // Handle an empty array of lists
    if (arr.empty())
        return nullptr;

    // Merge all lists using divide and conquer
    return mergeRange(arr, 0, arr.size() - 1);
}

int main()
{
    vector<vector<int>> lists = {{1, 4, 7}, {2, 8}, {3, 9}};
    vector<Node *> arr;

    // Convert arrays into linked lists
    for (const auto &row : lists)
    {
        Node *head = nullptr;
        Node *temp = nullptr;

        for (int x : row)
        {
            Node *newNode = new Node(x);

            if (head == nullptr)
            {
                head = newNode;
                temp = newNode;
            }
            else
            {
                temp->next = newNode;
                temp = temp->next;
            }
        }

        arr.push_back(head);
    }

    // Merge the k sorted linked lists
    Node *res = mergeKLists(arr);

    // Print the merged list
    while (res != nullptr)
    {
        cout << res->data;
        if (res->next != nullptr)
            cout << " -> ";
        res = res->next;
    }

    cout << '\n';

    return 0;
}
Java
class Node {
    int data;
    Node next;

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

class GFG {
    static Node mergeTwoLists(Node a, Node b)
    {
        Node dummy = new Node(-1);
        Node tail = dummy;

        // Merge both lists by selecting the smaller node
        while (a != null && b != null) {
            if (a.data <= b.data) {
                tail.next = a;
                a = a.next;
            }
            else {
                tail.next = b;
                b = b.next;
            }

            tail = tail.next;
        }

        // Attach the remaining nodes
        if (a != null)
            tail.next = a;
        else
            tail.next = b;

        return dummy.next;
    }

    static Node mergeRange(Node[] arr, int left, int right)
    {
        // If the range is empty
        if (left > right)
            return null;

        // If only one list remains
        if (left == right)
            return arr[left];

        // Divide the range into two halves
        int mid = left + (right - left) / 2;

        Node first = mergeRange(arr, left, mid);
        Node second = mergeRange(arr, mid + 1, right);

        // Merge the results of both halves
        return mergeTwoLists(first, second);
    }

    static Node mergeKLists(Node[] arr)
    {
        // Handle an empty array of lists
        if (arr.length == 0)
            return null;

        // Merge all lists using divide and conquer
        return mergeRange(arr, 0, arr.length - 1);
    }

    public static void main(String[] args)
    {
        int[][] lists = { { 1, 4, 7 }, { 2, 8 }, { 3, 9 } };

        Node[] arr = new Node[lists.length];

        // Convert arrays into linked lists
        for (int i = 0; i < lists.length; i++) {
            Node head = null;
            Node temp = null;

            for (int x : lists[i]) {
                Node newNode = new Node(x);

                if (head == null) {
                    head = newNode;
                    temp = newNode;
                }
                else {
                    temp.next = newNode;
                    temp = temp.next;
                }
            }

            arr[i] = head;
        }

        // Merge the k sorted linked lists
        Node res = mergeKLists(arr);

        // Print the merged list
        while (res != null) {
            System.out.print(res.data);
            if (res.next != null)
                System.out.print(" -> ");
            res = res.next;
        }

        System.out.println();
    }
}
Python
class Node:
    def __init__(self, x):
        self.data = x
        self.next = None


def mergeTwoLists(a, b):
    dummy = Node(-1)
    tail = dummy

    # Merge both lists by selecting the smaller node
    while a is not None and b is not None:
        if a.data <= b.data:
            tail.next = a
            a = a.next
        else:
            tail.next = b
            b = b.next

        tail = tail.next

    # Attach the remaining nodes
    if a is not None:
        tail.next = a
    else:
        tail.next = b

    return dummy.next


def mergeRange(arr, left, right):
    # If the range is empty
    if left > right:
        return None

    # If only one list remains
    if left == right:
        return arr[left]

    # Divide the range into two halves
    mid = left + (right - left) // 2

    first = mergeRange(arr, left, mid)
    second = mergeRange(arr, mid + 1, right)

    # Merge the results of both halves
    return mergeTwoLists(first, second)


def mergeKLists(arr):
    # Handle an empty array of lists
    if len(arr) == 0:
        return None

    # Merge all lists using divide and conquer
    return mergeRange(arr, 0, len(arr) - 1)


def main():
    lists = [[1, 4, 7], [2, 8], [3, 9]]
    arr = []

    # Convert arrays into linked lists
    for row in lists:
        head = None
        temp = None

        for x in row:
            newNode = Node(x)

            if head is None:
                head = newNode
                temp = newNode
            else:
                temp.next = newNode
                temp = temp.next

        arr.append(head)

    # Merge the k sorted linked lists
    res = mergeKLists(arr)

    # Print the merged list
    while res is not None:
        print(res.data, end="")
        if res.next is not None:
            print(" -> ", end="")
        res = res.next

    print()

# Driver Code
if __name__ == "__main__":
    main()
C#
using System;

class Node {
    public int data;
    public Node next;

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

class GFG {
    static Node mergeTwoLists(Node a, Node b)
    {
        Node dummy = new Node(-1);
        Node tail = dummy;

        // Merge both lists by selecting the smaller node
        while (a != null && b != null) {
            if (a.data <= b.data) {
                tail.next = a;
                a = a.next;
            }
            else {
                tail.next = b;
                b = b.next;
            }

            tail = tail.next;
        }

        // Attach the remaining nodes
        if (a != null)
            tail.next = a;
        else
            tail.next = b;

        return dummy.next;
    }

    static Node mergeRange(Node[] arr, int left, int right)
    {
        // If the range is empty
        if (left > right)
            return null;

        // If only one list remains
        if (left == right)
            return arr[left];

        // Divide the range into two halves
        int mid = left + (right - left) / 2;

        Node first = mergeRange(arr, left, mid);
        Node second = mergeRange(arr, mid + 1, right);

        // Merge the results of both halves
        return mergeTwoLists(first, second);
    }

    static Node mergeKLists(Node[] arr)
    {
        // Handle an empty array of lists
        if (arr.Length == 0)
            return null;

        // Merge all lists using divide and conquer
        return mergeRange(arr, 0, arr.Length - 1);
    }

    static void Main()
    {
        int[][] lists
            = { new int[] { 1, 4, 7 }, new int[] { 2, 8 },
                new int[] { 3, 9 } };

        Node[] arr = new Node[lists.Length];

        // Convert arrays into linked lists
        for (int i = 0; i < lists.Length; i++) {
            Node head = null;
            Node temp = null;

            foreach(int x in lists[i])
            {
                Node newNode = new Node(x);

                if (head == null) {
                    head = newNode;
                    temp = newNode;
                }
                else {
                    temp.next = newNode;
                    temp = temp.next;
                }
            }

            arr[i] = head;
        }

        // Merge the k sorted linked lists
        Node res = mergeKLists(arr);

        // Print the merged list
        while (res != null) {
            Console.Write(res.data);
            if (res.next != null)
                Console.Write(" -> ");
            res = res.next;
        }

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

function mergeTwoLists(a, b)
{
    let dummy = new Node(-1);
    let tail = dummy;

    // Merge both lists by selecting the smaller node
    while (a !== null && b !== null) {
        if (a.data <= b.data) {
            tail.next = a;
            a = a.next;
        }
        else {
            tail.next = b;
            b = b.next;
        }

        tail = tail.next;
    }

    // Attach the remaining nodes
    if (a !== null)
        tail.next = a;
    else
        tail.next = b;

    return dummy.next;
}

function mergeRange(arr, left, right)
{
    // If the range is empty
    if (left > right)
        return null;

    // If only one list remains
    if (left === right)
        return arr[left];

    // Divide the range into two halves
    let mid = left + Math.floor((right - left) / 2);

    let first = mergeRange(arr, left, mid);
    let second = mergeRange(arr, mid + 1, right);

    // Merge the results of both halves
    return mergeTwoLists(first, second);
}

function mergeKLists(arr)
{
    // Handle an empty array of lists
    if (arr.length === 0)
        return null;

    // Merge all lists using divide and conquer
    return mergeRange(arr, 0, arr.length - 1);
}

// Driver Code
function main()
{
    const lists = [ [ 1, 4, 7 ], [ 2, 8 ], [ 3, 9 ] ];
    const arr = [];

    // Convert arrays into linked lists
    for (const row of lists) {
        let head = null;
        let temp = null;

        for (const x of row) {
            const newNode = new Node(x);

            if (head === null) {
                head = newNode;
                temp = newNode;
            }
            else {
                temp.next = newNode;
                temp = temp.next;
            }
        }

        arr.push(head);
    }

    // Merge the k sorted linked lists
    let res = mergeKLists(arr);

    // Print the merged list
    let output = [];

    while (res !== null) {
        output.push(res.data);
        res = res.next;
    }

    console.log(output.join(" -> "));
}

main();

Output
1 -> 2 -> 3 -> 4 -> 7 -> 8 -> 9
Comment