Merge two sorted linked lists

Introduction

The linked list is one of the most important concepts to know while preparing for interviews. Having a good grasp of a linked list can be a huge plus point in coding interviews.

Problem Statement

In this problem, we will be given two sorted linked lists. We need to merge both lists such that the newly created list is also in sorted order.

Problem Statement Understanding

The problem statement is quite straightforward, we will be given two linked lists that are sorted in nature, and then we need to form a linked list using all the nodes of both linked lists such that the newly formed list is sorted in order.

Let's try to understand the problem with the help of examples.

  • Let the two sorted lists given to us be:

  • Now, the list that we need to return must contain all the nodes of both lists in sorted order.
  • So, the newly formed resultant list will be:

    Let’s take another example:
  • Let the two sorted lists given to us be 2→8→9→10→NULL and 11→13→17→NULL
  • For the above two sorted lists, the final linked list after merging will be 2→8→9→10→11→13→17→NULL
Some more examples

Sample Input 1:

  • list 1: 1→3→5→7
  • list 2: 2→4→6→8

Sample Output 1:
1→2→3→4→5→6→7→8

Sample Input 2:

  • list 1: 2→3→6→7→9
  • list 2: 1→5→8→11→19→31

Sample Output 2:
1→2→3→5→6→7→8→9→11→19→31

Now, I think from the above examples, the problem statement is clear. Let’s see how we can approach it.

Before moving to the approach section, try to think how you can approach this problem.

  • If stuck, no problem, we will thoroughly see how we can approach this problem in the next section.

Let’s move to the approach section.

Approach 1

  • We will make a recursive function that will create a sorted list out of two given sorted lists, containing all the nodes of both the given sorted list.
  • We will compare the head of both the lists and the one with a smaller head will be appearing at the current position and all other nodes will appear after that.
  • Now we will call the recursive function for the rest of the remaining nodes, and then we will attach the current node with the result from the recursive call, i.e., with the remaining node’s result.
  • If any one of the nodes is NULL, then we need to return the other list’s head from there.

Time Complexity: O(n), n is the number of nodes in both the list combined.
Space Complexity: O(n), n is the size of the recursive stack

The above approach works fine, but can we make our code more efficient in terms of memory.

  • The answer is yes, and to know how we can reduce the space complexity, read the below approach which uses constant memory.

Let’s jump to the next approach.

Approach 2

  • In this approach, we first reverse both the lists given to us as input.
  • Then we will create an empty list result.
  • We will initialize two pointers h1 and h2 to the head of list 1 and list 2, respectively.
  • Then we will iterate over both the lists while(h1 != NULL && h2!=NULL).
    • While iterating at every step, we will find the larger of the two h1 and h2 by comparing h1→data and h2→data.
    • We will insert the larger one of h1 and h2 at the front of the result list.
    • Then we will move ahead in the list whose node was larger (larger node - we will compare using h1→data and h2→data).
  • If any of the h1 or h2 becomes NULL, we will insert all the remaining node’s of the other list into the result list.
  • At last, we will have a new list that will be sorted given by result.

Time Complexity: O(n), n is the number of nodes in both the list combined.
Space Complexity: O(1)

The above approach uses constant space, but it will iterate on both lists two times in the worst case.

  • First, when the list is reversed and the second time when we are iterating to sort the list.

Can we do even better?

  • The answer is yes, and to know the solution, read the below approach.

Approach 3

  • In this approach, we create a dummy node with INT_MIN value that will represent the tail of our new list.
  • Then we will iterate on both the lists while both of them is not NULL.
  • Then we need to check the node with a smaller value and insert it after the tail of our new list, and then update the tail of the list.
  • At last, If the first list has reached NULL, then we need to attach the remaining elements of the second list after the tail and vice versa.

Algorithm

  • Create a node named dummy having INT_MIN as its data.
  • Initialize a pointer named tail with the address of the above-created dummy variable.
  • Initialize two pointers named l1 and l2 with the heads of both the lists, respectively.
  • Until both l1 and l2 are not equal to NULL, run a while loop in which we need to check which pointer points to a smaller node.
    • If l1 points to a smaller node, we need to attach l1 at the end of the tail and update l1 with its next node’s address.
    • If l2 points to a smaller node, we need to attach l2 at the end of the tail and update l2 with its next node’s address
    • Then, we need to advance the tail pointer to its next node
  • After the while loop ends, we need to check whether l1 or l2 is NULL or not.
    • If l2 is NULL, we need to assign tail→next to l1.
    • If l1 is NULL, we need to assign tail→next to l1.
  • Finally, we return the dummy node’s next node as the head of our newly created list.

Dry Run

Code Implementation

#include 
#include
using namespace std;

/* Class with constructor for a node of Linked list */
class Node {
    public:
    int data;
    Node* next;
    // constructor
    Node(int x){
        data = x;
        next = NULL;
}
};

/* Using this function we will be printing the data of the linked list */
void print(Node* head)
{
    Node* curr = head;
    while (curr != NULL) {
        cout << curr->data << " -> ";
        curr = curr->next;
    }
    cout<<"NULL"<data < l2->data) {
                tail->next = l1;
                l1 = l1->next;
            } else {
                tail->next = l2;
                l2 = l2->next;
            }
            tail = tail->next;
        }

        tail->next = l1 ? l1 : l2;
        return dummy.next;
    }


/* Main function */
int main()
{
    Node *list1 = new Node(2);
    list1->next = new Node(3);
    list1->next->next = new Node(5);
    list1->next->next->next = new Node(9);

    Node *list2 = new Node(1);
    list2->next = new Node(4);
    list2->next->next = new Node(8);
    
    cout<<"Original linked list 1: "<

						 

#include
#include
#include
  
/* Link list node */
struct Node
{
    int data;
    struct Node* next;
};
  
/* pull off the front node of the source and put it in dest */
void MoveNode(struct Node** destRef, struct Node** sourceRef);
  
/* Takes two lists sorted in increasing order, and splices
   their nodes together to make one big sorted list which
   is returned.  */
struct Node* SortedMerge(struct Node* a, struct Node* b)
{
    /* a dummy first node to hang the result on */
    struct Node dummy;
  
    /* tail points to the last result node  */
    struct Node* tail = &dummy;
  
    /* so tail->next is the place to add new nodes
      to the result. */
    dummy.next = NULL;
    while (1)
    {
        if (a == NULL)
        {
            /* if either list runs out, use the
               other list */
            tail->next = b;
            break;
        }
        else if (b == NULL)
        {
            tail->next = a;
            break;
        }
        if (a->data <= b->data)
            MoveNode(&(tail->next), &a);
        else
            MoveNode(&(tail->next), &b);
  
        tail = tail->next;
    }
    return(dummy.next);
}
  
/* UTILITY FUNCTIONS */
/* MoveNode() function takes the node from the front of the
   source, and move it to the front of the dest.
   It is an error to call this with the source list empty.
  
   Before calling MoveNode():
   source == {1, 2, 3}
   dest == {1, 2, 3}
  
   After calling MoveNode():
   source == {2, 3}
   dest == {1, 1, 2, 3} */
void MoveNode(struct Node** destRef, struct Node** sourceRef)
{
    /* the front source node  */
    struct Node* newNode = *sourceRef;
    assert(newNode != NULL);
  
    /* Advance the source pointer */
    *sourceRef = newNode->next;
  
    /* Link the old dest off the new node */
    newNode->next = *destRef;
  
    /* Move dest to point to the new node */
    *destRef = newNode;
}
  
  
/* Function to insert a node at the beginning of the
   linked list */
void push(struct Node** head_ref, int new_data)
{
    /* allocate node */
    struct Node* new_node =
        (struct Node*) malloc(sizeof(struct Node));
  
    /* put in the data  */
    new_node->data  = new_data;
  
    /* link the old list off the new node */
    new_node->next = (*head_ref);
  
    /* move the head to point to the new node */
    (*head_ref)    = new_node;
}
  
/* Function to print nodes in a given linked list */
void printList(struct Node *node)
{
    while (node!=NULL)
    {
        printf("%d ", node->data);
        node = node->next;
    }
}
  
/* Driver program to test above functions*/
int main()
{
    /* Start with the empty list */
    struct Node* res = NULL;
    struct Node* a = NULL;
    struct Node* b = NULL;
  
    /* Let us create two sorted linked lists to test
      the functions
       Created lists, a: 5->10->15,  b: 2->3->20 */
    push(&a, 15);
    push(&a, 10);
    push(&a, 5);
  
    push(&b, 20);
    push(&b, 3);
    push(&b, 2);
  
    /* Remove duplicates from linked list */
    res = SortedMerge(a, b);
  
    printf("Merged Linked List is: \n");
    printList(res);
  
    return 0;
}


class Node
{
	int data;
	Node next;
	Node(int d) {data = d;
				next = null;}
}
class Sort
{
    Node sortedMerge(Node headA, Node headB)
    {
	    /* a dummy first node to chang the result on */
	    Node dummyNode = new Node(0);
	    /* tail points to the last result node */
	    Node tail = dummyNode;
	    while(true)
	    {
		    /* if either list runs out,
		    use the other list */
		    if(headA == null)
		    {
			    tail.next = headB;
			    break;
		    }
		    if(headB == null)
		    {
			    tail.next = headA;
			    break;
		    }
		    /* Compare the data of the two
		    lists whichever lists' data is
		    smaller, append it into tail and
		    advance the head to the next Node*/
		    if(headA.data <= headB.data)
		    {
			    tail.next = headA;
			    headA = headA.next;
		    }
		    else
		    {
			    tail.next = headB;
			    headB = headB.next;
		    }
		    tail = tail.next;
	    }
	    return dummyNode.next;
    }
}	
class Merge2Sorted
{
    Node head;
    public void addToTheLast(Node node)
    {
	    if (head == null)
	    {
		    head = node;
	    }
	    else
	    {
		    Node temp = head;
		    while (temp.next != null)
			    temp = temp.next;
		    temp.next = node;
	    }
    }
    void printList()
    {
    	Node temp = head;
	    while (temp != null)
	    {
		    System.out.print(temp.data + " ");
		    temp = temp.next;
	    }
	    System.out.println();
    }
    // Driver Code
    public static void main(String args[])
    {   
	
	Merge2Sorted llist1 = new Merge2Sorted();
	Merge2Sorted llist2 = new Merge2Sorted();
	
	// Node head1 = new Node(5);
	llist1.addToTheLast(new Node(5));
	llist1.addToTheLast(new Node(10));
	llist1.addToTheLast(new Node(15));
	
	// Node head2 = new Node(2);
	llist2.addToTheLast(new Node(2));
	llist2.addToTheLast(new Node(3));
	llist2.addToTheLast(new Node(20));
	
	
	llist1.head = new Sort().sortedMerge(llist1.head,
										llist2.head);
	llist1.printList();	
	
    }
}

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

class LinkedList:
	def __init__(self):
		self.head = None

	def printList(self):
		temp = self.head
		while temp:
			print(temp.data, end=" ")
			temp = temp.next

	def addToList(self, newData):
		newNode = Node(newData)
		if self.head is None:
			self.head = newNode
			return

		last = self.head
		while last.next:
			last = last.next

		last.next = newNode

def mergeLists(headA, headB):

	dummyNode = Node(0)

	tail = dummyNode
	while True:

		if headA is None:
			tail.next = headB
			break
		if headB is None:
			tail.next = headA
			break

		if headA.data <= headB.data:
			tail.next = headA
			headA = headA.next
		else:
			tail.next = headB
			headB = headB.next

		tail = tail.next

	return dummyNode.next


listA = LinkedList()
listB = LinkedList()

listA.addToList(2)
listA.addToList(3)
listA.addToList(5)
listA.addToList(9)

listB.addToList(1)
listB.addToList(4)
listB.addToList(8)

print("Original linked list 1:")
listA.printList()

print("\nOriginal linked list 2:")
listB.printList()
listA.head = mergeLists(listA.head, listB.head)

print("\nMerged Linked List is:")
listA.printList()

Output

Original linked list 1:
2 -> 3 -> 5 -> 9 -> NULL
Original linked list 2:
1 -> 4 -> 8 -> NULL
Merged sorted linked list:
1 -> 2 -> 3 -> 4 -> 5 -> 8 -> 9 -> NULL

Time Complexity: O(n), where n is the total number of nodes in both the lists.
[forminator_quiz id="5081"]

So, in this blog, we have tried to explain how you can merge two sorted linked lists in the most optimal way. This is a basic problem and is good for strengthening your concepts in LinkedList and if you want to practice more such problems, you can checkout Prepbytes (Linked List).

Leave a Reply

Your email address will not be published. Required fields are marked *