Wednesday, July 3, 2024
HomeData ModellingData Structure & AlgorithmC++ Program To Merge K Sorted Linked Lists – Set 1

C++ Program To Merge K Sorted Linked Lists – Set 1

Given K sorted linked lists of size N each, merge them and print the sorted output.

Examples: 

Input: k = 3, n =  4
list1 = 1->3->5->7->NULL
list2 = 2->4->6->8->NULL
list3 = 0->9->10->11->NULL

Output: 0->1->2->3->4->5->6->7->8->9->10->11
Merged lists in a sorted order 
where every element is greater 
than the previous element.

Input: k = 3, n =  3
list1 = 1->3->7->NULL
list2 = 2->4->8->NULL
list3 = 9->10->11->NULL

Output: 1->2->3->4->7->8->9->10->11
Merged lists in a sorted order 
where every element is greater 
than the previous element.

Method 1 (Simple):

Approach: 
A Simple Solution is to initialize the result as the first list. Now traverse all lists starting from the second list. Insert every node of the currently traversed list into result in a sorted way.  

C++




// C++ program to merge k sorted
// linked lists of size n each
#include <bits/stdc++.h>
using namespace std;
 
// A Linked List node
struct Node
{
    int data;
    Node* next;
};
 
/* Function to print nodes in a
   given linked list */
void printList(Node* node)
{
    while (node != NULL)
    {
        printf("%d ", node->data);
        node = node->next;
    }
}
 
// The main function that takes an
// array of lists arr[0..last] and
// generates the sorted output
Node* mergeKLists(Node* arr[],
                  int last)
{
    // Traverse from second list to last
    for (int i = 1; i <= last; i++)
    {
        while (true)
        {
            // Head of both the lists,
            // 0 and ith list.
            Node *head_0 = arr[0],
                 *head_i = arr[i];
 
            // Break if list ended
            if (head_i == NULL)
                break;
 
            // Smaller than first element
            if (head_0->data >= head_i->data)
            {
                arr[i] = head_i->next;
                head_i->next = head_0;
                arr[0] = head_i;
            }
            else
                // Traverse the first list
                while (head_0->next != NULL)
                {
                    // Smaller than next element
                    if (head_0->next->data >=
                        head_i->data)
                    {
                        arr[i] = head_i->next;
                        head_i->next = head_0->next;
                        head_0->next = head_i;
                        break;
                    }
                    // go to next node
                    head_0 = head_0->next;
 
                    // if last node
                    if (head_0->next == NULL)
                    {
                        arr[i] = head_i->next;
                        head_i->next = NULL;
                        head_0->next = head_i;
                        head_0->next->next = NULL;
                        break;
                    }
                }
        }
    }
    return arr[0];
}
 
// Utility function to create
// a new node.
Node* newNode(int data)
{
    struct Node* temp = new Node;
    temp->data = data;
    temp->next = NULL;
    return temp;
}
 
// Driver code
int main()
{
    // Number of linked lists
    int k = 3;
 
    // Number of elements in each list
    int n = 4;
 
    // an array of pointers storing the
    // head nodes of the linked lists
    Node* arr[k];
 
    arr[0] = newNode(1);
    arr[0]->next = newNode(3);
    arr[0]->next->next = newNode(5);
    arr[0]->next->next->next = newNode(7);
 
    arr[1] = newNode(2);
    arr[1]->next = newNode(4);
    arr[1]->next->next = newNode(6);
    arr[1]->next->next->next = newNode(8);
 
    arr[2] = newNode(0);
    arr[2]->next = newNode(9);
    arr[2]->next->next = newNode(10);
    arr[2]->next->next->next = newNode(11);
 
    // Merge all lists
    Node* head = mergeKLists(arr, k - 1);
 
    printList(head);
 
    return 0;
}


Output:

0 1 2 3 4 5 6 7 8 9 10 11

Complexity Analysis: 

  • Time complexity: O(nk2)
  • Auxiliary Space: O(1). 
    As no extra space is required.

Method 2: Min Heap
A Better solution is to use Min Heap-based solution which is discussed here for arrays. The time complexity of this solution would be O(nk Log k)
Method 3: Divide and Conquer
In this post, Divide and Conquer approach is discussed. This approach doesn’t require extra space for heap and works in O(nk Log k)
It is known that merging of two linked lists can be done in O(n) time and O(n) space. 

  1. The idea is to pair up K lists and merge each pair in linear time using O(n) space.
  2. After the first cycle, K/2 lists are left each of size 2*N. After the second cycle, K/4 lists are left each of size 4*N and so on.
  3. Repeat the procedure until we have only one list left.

Below is the implementation of the above idea. 

C++




// C++ program to merge k sorted
// linked lists of size n each
#include <bits/stdc++.h>
using namespace std;
 
// A Linked List node
struct Node
{
    int data;
    Node* next;
};
 
/* Function to print nodes in a
   given linked list */
void printList(Node* node)
{
    while (node != NULL)
    {
        printf("%d ", node->data);
        node = node->next;
    }
}
 
/* Takes two lists sorted in increasing order,
   and merge their nodes together to make one
   big sorted list. Below function takes O(n)
   extra space for recursive calls, */
Node* SortedMerge(Node* a, Node* b)
{
    Node* result = NULL;
 
    // Base cases
    if (a == NULL)
        return (b);
    else if (b == NULL)
        return (a);
 
    // Pick either a or b, and recur
    if (a->data <= b->data)
    {
        result = a;
        result->next = SortedMerge(a->next, b);
    }
    else
    {
        result = b;
        result->next = SortedMerge(a, b->next);
    }
 
    return result;
}
 
// The main function that takes an
// array of lists arr[0..last] and
// generates the sorted output
Node* mergeKLists(Node* arr[], int last)
{
    // Repeat until only one list is left
    while (last != 0)
    {
        int i = 0, j = last;
 
        // (i, j) forms a pair
        while (i < j)
        {
            // merge List i with List j and
            // store merged list in List i
            arr[i] = SortedMerge(arr[i], arr[j]);
 
            // consider next pair
            i++, j--;
 
            // If all pairs are merged, update
            // last
            if (i >= j)
                last = j;
        }
    }
 
    return arr[0];
}
 
// Utility function to create
// a new node.
Node* newNode(int data)
{
    struct Node* temp = new Node;
    temp->data = data;
    temp->next = NULL;
    return temp;
}
 
// Driver code
int main()
{
    // Number of linked lists
    int k = 3;
 
    // Number of elements in
    // each list
    int n = 4;
 
    // An array of pointers storing
    // the head nodes of the linked lists
    Node* arr[k];
 
    arr[0] = newNode(1);
    arr[0]->next = newNode(3);
    arr[0]->next->next = newNode(5);
    arr[0]->next->next->next = newNode(7);
 
    arr[1] = newNode(2);
    arr[1]->next = newNode(4);
    arr[1]->next->next = newNode(6);
    arr[1]->next->next->next = newNode(8);
 
    arr[2] = newNode(0);
    arr[2]->next = newNode(9);
    arr[2]->next->next = newNode(10);
    arr[2]->next->next->next = newNode(11);
 
    // Merge all lists
    Node* head = mergeKLists(arr, k - 1);
 
    printList(head);
 
    return 0;
}


Output:

0 1 2 3 4 5 6 7 8 9 10 11

Complexity Analysis: 

Assuming N(n*k) is the total number of nodes, n is the size of each linked list, and k is the total number of linked lists.

  • Time Complexity: O(N*log k) or O(n*k*log k)
    As outer while loop in function mergeKLists() runs log k times and every time it processes n*k elements.
  • Auxiliary Space: O(N) or O(n*k)
    Because recursion is used in SortedMerge() and to merge the final 2 linked lists of size N/2, N recursive calls will be made.

Please refer complete article on Merge K sorted linked lists | Set 1 for more details!

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Last Updated :
15 Feb, 2023
Like Article
Save Article


Previous

<!–

8 Min Read | Java

–>


Next


<!–

8 Min Read | Java

–>

Nango Kalahttps://www.kala.co.za
Experienced Support Engineer with a demonstrated history of working in the information technology and services industry. Skilled in Microsoft Excel, Customer Service, Microsoft Word, Technical Support, and Microsoft Office. Strong information technology professional with a Microsoft Certificate Solutions Expert (Privet Cloud) focused in Information Technology from Broadband Collage Of Technology.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments