Open In App

C++ Program To Merge Two Sorted Lists (In-Place)

Last Updated : 27 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Write a C++ program to merge two sorted linked lists into a single sorted linked list in place (i.e. without using extra space).

Examples:

Input: List1: 5 -> 7 -> 9, list2: 4 -> 6 -> 8
Output: 4->5->6->7->8->9

Input: List1: 1 -> 3 -> 5 -> 7, List2: 2 -> 4
Output: 1 -> 2 -> 3 -> 4 -> 5 -> 7

Algorithm to Merge Two Sorted Lists (In-Place) in C++

Merging two sorted linked lists using recursion involves combining them into one list while maintaining the order of the elements. The approach to merge two sorted linked list in place is as follows:

  1. Start from the beginning of the two linked list
  2. If both the elements are NULL return null. Otherwise,
  3. Compare the current elements of both linked lists.
  4. Set the smaller element’s next pointer to the element that is return by the recursive call where we pass same linked lists except omitting the smaller element. This call will return the next smaller element between the linked lists.
  5. Return the smaller element.
  6. If one list ends before another, return the other list.

To know more methods for merging, refer to the article – Merge two sorted lists (in-place)

Implementation

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

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

Node* mergeInPlace(Node* h1, Node* h2) {
  	
  	// Return NULL when both of the linked list are empty
  	if (!h1 && !h2) return NULL;
  	
  	// If one list ends, returns the remaining one.
    if (!h1) return h2;
    if (!h2) return h1;

    // Return and set the next pointer of the smaller node
    if (h1->data < h2->data) {
        h1->next = mergeInPlace(h1->next, h2);
        return h1;
    }
    else {
        h2->next = mergeInPlace(h1, h2->next);
        return h2;
    }
}

int main() {
  
  	// First Linked List: 1 -> 3 -> 5
    Node* list1 = new Node(1);
    list1->next = new Node(3);
    list1->next->next = new Node(5);
    
  	// Second Linked List: 0 ->2 -> 4
    Node* list2 = new Node(0);
    list2->next = new Node(2);
    list2->next->next = new Node(4);

    Node* result = mergeInPlace(list1, list2);
	
  	// Printing the resultant list
  	Node* temp = result;
    while (temp != NULL) {
        printf("%d  ", temp->data);
        temp = temp->next;
    }
    return 0;
}

Output
0  1  2  3  4  5  

Time Complexity: O (N + M), where N is the size of first list and M is the size of second list.
Auxiliary Space: O (N + M), needed by recursion call stack.

We can implement this using iteration too which saves the stack space consumed by this implementation. But that approach is complex to understand. Refer to this article for it – Merge two sorted lists (in-place)



Next Article

Similar Reads