Open In App

Sorted merge of two sorted doubly circular linked lists

Improve
Improve
Like Article
Like
Save
Share
Report

Given two sorted Doubly circular Linked List containing n1 and n2 nodes respectively. The problem is to merge the two lists such that resultant list is also in sorted order.
Example: 

List 1: 
 

List 2: 
 

Final list: 

Approach: Following are the steps:

  1. If head1 == NULL, return head2.
  2. If head2 == NULL, return head1.
  3. Let last1 and last2 be the last nodes of the two lists respectively. They can be obtained with the help of the previous links of the first nodes.
  4. Get pointer to the node which will be the last node of the final list. If last1.data < last2.data, then last_node = last2, Else last_node = last1.
  5. Update last1.next = last2.next = NULL.
  6. Now merge the two lists as two sorted doubly linked list are being merged. Refer merge procedure of this post. Let the first node of the final list be finalHead.
  7. Update finalHead.prev = last_node and last_node.next = finalHead.
  8. Return finalHead.

Implementation:

C++




// C++ implementation for Sorted merge of two
// sorted doubly circular linked list
#include <bits/stdc++.h>
using namespace std;
 
struct Node {
    int data;
    Node *next, *prev;
};
 
// A utility function to insert a new node at the
// beginning of doubly circular linked list
void insert(Node** head_ref, int data)
{
    // allocate space
    Node* new_node = new Node;
 
    // put in the data
    new_node->data = data;
 
    // if list is empty
    if (*head_ref == NULL) {
        new_node->next = new_node;
        new_node->prev = new_node;
    }
 
    else {
 
        // pointer points to last Node
        Node* last = (*head_ref)->prev;
 
        // setting up previous and next of new node
        new_node->next = *head_ref;
        new_node->prev = last;
 
        // update next and previous pointers of head_ref
        // and last.
        last->next = (*head_ref)->prev = new_node;
    }
 
    // update head_ref pointer
    *head_ref = new_node;
}
 
// function for Sorted merge of two
// sorted doubly linked list
Node* merge(Node* first, Node* second)
{
    // If first list is empty
    if (!first)
        return second;
 
    // If second list is empty
    if (!second)
        return first;
 
    // Pick the smaller value and adjust
    // the links
    if (first->data < second->data) {
        first->next = merge(first->next, second);
        first->next->prev = first;
        first->prev = NULL;
        return first;
    }
    else {
        second->next = merge(first, second->next);
        second->next->prev = second;
        second->prev = NULL;
        return second;
    }
}
 
// function for Sorted merge of two sorted
// doubly circular linked list
Node* mergeUtil(Node* head1, Node* head2)
{
    // if 1st list is empty
    if (!head1)
        return head2;
 
    // if 2nd list is empty
    if (!head2)
        return head1;
 
    // get pointer to the node which will be the
    // last node of the final list
    Node* last_node;
    if (head1->prev->data < head2->prev->data)
        last_node = head2->prev;
    else
        last_node = head1->prev;
 
    // store NULL to the 'next' link of the last nodes
    // of the two lists
    head1->prev->next = head2->prev->next = NULL;
 
    // sorted merge of head1 and head2
    Node* finalHead = merge(head1, head2);
 
    // 'prev' of 1st node pointing the last node
    // 'next' of last node pointing to 1st node
    finalHead->prev = last_node;
    last_node->next = finalHead;
 
    return finalHead;
}
 
// function to print the list
void printList(Node* head)
{
    Node* temp = head;
 
    while (temp->next != head) {
        cout << temp->data << " ";
        temp = temp->next;
    }
    cout << temp->data << " ";
}
 
// Driver program to test above
int main()
{
    Node *head1 = NULL, *head2 = NULL;
 
    // list 1:
    insert(&head1, 8);
    insert(&head1, 5);
    insert(&head1, 3);
    insert(&head1, 1);
 
    // list 2:
    insert(&head2, 11);
    insert(&head2, 9);
    insert(&head2, 7);
    insert(&head2, 2);
 
    Node* newHead = mergeUtil(head1, head2);
 
    cout << "Final Sorted List: ";
    printList(newHead);
 
    return 0;
}


Java




// Java implementation for Sorted merge of two
// sorted doubly circular linked list
import java.util.*;
import java.io.*;
 
class GFG
{
     
static class Node
{
    int data;
    Node next, prev;
};
 
// A utility function to insert a new node at the
// beginning of doubly circular linked list
static Node insert(Node head_ref, int data)
{
    // allocate space
    Node new_node = new Node();
 
    // put in the data
    new_node.data = data;
 
    // if list is empty
    if (head_ref == null)
    {
        new_node.next = new_node;
        new_node.prev = new_node;
    }
 
    else
    {
 
        // pointer points to last Node
        Node last = (head_ref).prev;
 
        // setting up previous and next of new node
        new_node.next = head_ref;
        new_node.prev = last;
 
        // update next and previous pointers of head_ref
        // and last.
        last.next = (head_ref).prev = new_node;
    }
 
    // update head_ref pointer
    head_ref = new_node;
    return head_ref;
}
 
// function for Sorted merge of two
// sorted doubly linked list
static Node merge(Node first, Node second)
{
    // If first list is empty
    if (first == null)
        return second;
 
    // If second list is empty
    if (second == null)
        return first;
 
    // Pick the smaller value and adjust
    // the links
    if (first.data < second.data)
    {
        first.next = merge(first.next, second);
        first.next.prev = first;
        first.prev = null;
        return first;
    }
    else
    {
        second.next = merge(first, second.next);
        second.next.prev = second;
        second.prev = null;
        return second;
    }
}
 
// function for Sorted merge of two sorted
// doubly circular linked list
static Node mergeUtil(Node head1, Node head2)
{
    // if 1st list is empty
    if (head1 == null)
        return head2;
 
    // if 2nd list is empty
    if (head2 == null)
        return head1;
 
    // get pointer to the node which will be the
    // last node of the final list
    Node last_node;
    if (head1.prev.data < head2.prev.data)
        last_node = head2.prev;
    else
        last_node = head1.prev;
 
    // store null to the 'next' link of the last nodes
    // of the two lists
    head1.prev.next = head2.prev.next = null;
 
    // sorted merge of head1 and head2
    Node finalHead = merge(head1, head2);
 
    // 'prev' of 1st node pointing the last node
    // 'next' of last node pointing to 1st node
    finalHead.prev = last_node;
    last_node.next = finalHead;
 
    return finalHead;
}
 
// function to print the list
static void printList(Node head)
{
    Node temp = head;
 
    while (temp.next != head)
    {
        System.out.print ( temp.data+ " ");
        temp = temp.next;
    }
    System.out.print ( temp.data + " ");
}
 
// Driver code
public static void main(String args[])
{
    Node head1 = null, head2 = null;
 
    // list 1:
    head1 = insert(head1, 8);
    head1 = insert(head1, 5);
    head1 = insert(head1, 3);
    head1 = insert(head1, 1);
 
    // list 2:
    head2 = insert(head2, 11);
    head2 = insert(head2, 9);
    head2 = insert(head2, 7);
    head2 = insert(head2, 2);
 
    Node newHead = mergeUtil(head1, head2);
 
    System.out.print( "Final Sorted List: ");
    printList(newHead);
}
}
 
// This code is contributed by Arnab Kundu


Python3




    # Python3 implementation for Sorted merge
# of two sorted doubly circular linked list
import math
 
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
        self.prev = None
 
# A utility function to insert
# a new node at the beginning
# of doubly circular linked list
def insert(head_ref, data):
     
    # allocate space
    new_node = Node(data)
 
    # put in the data
    new_node.data = data
 
    # if list is empty
    if (head_ref == None):
        new_node.next = new_node
        new_node.prev = new_node
     
    else :
 
        # pointer points to last Node
        last = head_ref.prev
 
        # setting up previous and
        # next of new node
        new_node.next = head_ref
        new_node.prev = last
 
        # update next and previous pointers
        # of head_ref and last.
        last.next = new_node
        head_ref.prev = new_node
     
    # update head_ref pointer
    head_ref = new_node
    return head_ref
 
# function for Sorted merge of two
# sorted doubly linked list
def merge(first, second):
     
    # If first list is empty
    if (first == None):
        return second
 
    # If second list is empty
    if (second == None):
        return first
 
    # Pick the smaller value and
    # adjust the links
    if (first.data < second.data) :
        first.next = merge(first.next,
                           second)
        first.next.prev = first
        first.prev = None
        return first
     
    else :
        second.next = merge(first,
                            second.next)
        second.next.prev = second
        second.prev = None
        return second
     
# function for Sorted merge of two sorted
# doubly circular linked list
def mergeUtil(head1, head2):
     
    # if 1st list is empty
    if (head1 == None):
        return head2
 
    # if 2nd list is empty
    if (head2 == None):
        return head1
 
    # get pointer to the node
    # which will be the last node
    # of the final list last_node
    if (head1.prev.data < head2.prev.data):
        last_node = head2.prev
    else:
        last_node = head1.prev
 
    # store None to the 'next' link of
    # the last nodes of the two lists
    head1.prev.next = None
    head2.prev.next = None
 
    # sorted merge of head1 and head2
    finalHead = merge(head1, head2)
 
    # 'prev' of 1st node pointing the last node
    # 'next' of last node pointing to 1st node
    finalHead.prev = last_node
    last_node.next = finalHead
 
    return finalHead
 
# function to print the list
def printList(head):
    temp = head
 
    while (temp.next != head):
        print(temp.data, end = " ")
        temp = temp.next
     
    print(temp.data, end = " ")
 
# Driver Code
if __name__=='__main__':
    head1 = None
    head2 = None
 
    # list 1:
    head1 = insert(head1, 8)
    head1 = insert(head1, 5)
    head1 = insert(head1, 3)
    head1 = insert(head1, 1)
 
    # list 2:
    head2 = insert(head2, 11)
    head2 = insert(head2, 9)
    head2 = insert(head2, 7)
    head2 = insert(head2, 2)
 
    newHead = mergeUtil(head1, head2)
 
    print("Final Sorted List: ", end = "")
    printList(newHead)
 
# This code is contributed by Srathore


C#




// C# implementation for Sorted merge of two
// sorted doubly circular linked list
using System;
 
class GFG
{
     
public class Node
{
    public int data;
    public Node next, prev;
};
 
// A utility function to insert a new node at the
// beginning of doubly circular linked list
static Node insert(Node head_ref, int data)
{
    // allocate space
    Node new_node = new Node();
 
    // put in the data
    new_node.data = data;
 
    // if list is empty
    if (head_ref == null)
    {
        new_node.next = new_node;
        new_node.prev = new_node;
    }
 
    else
    {
 
        // pointer points to last Node
        Node last = (head_ref).prev;
 
        // setting up previous and next of new node
        new_node.next = head_ref;
        new_node.prev = last;
 
        // update next and previous pointers of head_ref
        // and last.
        last.next = (head_ref).prev = new_node;
    }
 
    // update head_ref pointer
    head_ref = new_node;
    return head_ref;
}
 
// function for Sorted merge of two
// sorted doubly linked list
static Node merge(Node first, Node second)
{
    // If first list is empty
    if (first == null)
        return second;
 
    // If second list is empty
    if (second == null)
        return first;
 
    // Pick the smaller value and adjust
    // the links
    if (first.data < second.data)
    {
        first.next = merge(first.next, second);
        first.next.prev = first;
        first.prev = null;
        return first;
    }
    else
    {
        second.next = merge(first, second.next);
        second.next.prev = second;
        second.prev = null;
        return second;
    }
}
 
// function for Sorted merge of two sorted
// doubly circular linked list
static Node mergeUtil(Node head1, Node head2)
{
    // if 1st list is empty
    if (head1 == null)
        return head2;
 
    // if 2nd list is empty
    if (head2 == null)
        return head1;
 
    // get pointer to the node which will be the
    // last node of the final list
    Node last_node;
    if (head1.prev.data < head2.prev.data)
        last_node = head2.prev;
    else
        last_node = head1.prev;
 
    // store null to the 'next' link of the last nodes
    // of the two lists
    head1.prev.next = head2.prev.next = null;
 
    // sorted merge of head1 and head2
    Node finalHead = merge(head1, head2);
 
    // 'prev' of 1st node pointing the last node
    // 'next' of last node pointing to 1st node
    finalHead.prev = last_node;
    last_node.next = finalHead;
 
    return finalHead;
}
 
// function to print the list
static void printList(Node head)
{
    Node temp = head;
 
    while (temp.next != head)
    {
        Console.Write(temp.data + " ");
        temp = temp.next;
    }
    Console.Write(temp.data + " ");
}
 
// Driver code
public static void Main()
{
    Node head1 = null, head2 = null;
 
    // list 1:
    head1 = insert(head1, 8);
    head1 = insert(head1, 5);
    head1 = insert(head1, 3);
    head1 = insert(head1, 1);
 
    // list 2:
    head2 = insert(head2, 11);
    head2 = insert(head2, 9);
    head2 = insert(head2, 7);
    head2 = insert(head2, 2);
 
    Node newHead = mergeUtil(head1, head2);
 
    Console.Write( "Final Sorted List: ");
    printList(newHead);
}
}
 
// This code is contributed by Princi Singh


Javascript




<script>
// javascript implementation for Sorted merge of two
// sorted doubly circular linked list    
class Node
{
constructor()
{
         this.data = 0;
         this.next= this.prev = null;
}
}
 
    // A utility function to insert a new node at the
    // beginning of doubly circular linked list
    function insert( head_ref, data)
    {
     
        // allocate space
         new_node = new Node();
 
        // put in the data
        new_node.data = data;
 
        // if list is empty
        if (head_ref == null)
        {
            new_node.next = new_node;
            new_node.prev = new_node;
        }
 
        else
        {
 
            // pointer points to last Node
             last = (head_ref).prev;
 
            // setting up previous and next of new node
            new_node.next = head_ref;
            new_node.prev = last;
 
            // update next and previous pointers of head_ref
            // and last.
            last.next = (head_ref).prev = new_node;
        }
 
        // update head_ref pointer
        head_ref = new_node;
        return head_ref;
    }
 
    // function for Sorted merge of two
    // sorted doubly linked list
    function merge( first,  second)
    {
     
        // If first list is empty
        if (first == null)
            return second;
 
        // If second list is empty
        if (second == null)
            return first;
 
        // Pick the smaller value and adjust
        // the links
        if (first.data < second.data) {
            first.next = merge(first.next, second);
            first.next.prev = first;
            first.prev = null;
            return first;
        } else {
            second.next = merge(first, second.next);
            second.next.prev = second;
            second.prev = null;
            return second;
        }
    }
 
    // function for Sorted merge of two sorted
    // doubly circular linked list
    function mergeUtil( head1,  head2)
    {
     
        // if 1st list is empty
        if (head1 == null)
            return head2;
 
        // if 2nd list is empty
        if (head2 == null)
            return head1;
 
        // get pointer to the node which will be the
        // last node of the final list
         last_node = null;
        if (head1.prev.data < head2.prev.data)
            last_node = head2.prev;
        else
            last_node = head1.prev;
 
        // store null to the 'next' link of the last nodes
        // of the two lists
        head1.prev.next = head2.prev.next = null;
 
        // sorted merge of head1 and head2
         finalHead = merge(head1, head2);
 
        // 'prev' of 1st node pointing the last node
        // 'next' of last node pointing to 1st node
        finalHead.prev = last_node;
        last_node.next = finalHead;
 
        return finalHead;
    }
 
    // function to print the list
    function printList( head) {
         temp = head;
 
        while (temp.next != head) {
            document.write(temp.data + " ");
            temp = temp.next;
        }
        document.write(temp.data + " ");
    }
 
    // Driver code
     
         head1 = null, head2 = null;
 
        // list 1:
        head1 = insert(head1, 8);
        head1 = insert(head1, 5);
        head1 = insert(head1, 3);
        head1 = insert(head1, 1);
 
        // list 2:
        head2 = insert(head2, 11);
        head2 = insert(head2, 9);
        head2 = insert(head2, 7);
        head2 = insert(head2, 2);
 
         newHead = mergeUtil(head1, head2);
 
        document.write("Final Sorted List: ");
        printList(newHead);
 
// This code is contributed by umadevi9616
</script>


Output

Final Sorted List: 1 2 3 5 7 8 9 11 





Time Complexity: O(n1 + n2).
 Auxiliary Space: O(n1+n2)

METHOD 2:Using deque module

APPROACH:

The approach used in the code is to convert both the linked lists into two deques and then merge these deques into a new deque which would contain all the elements of the two linked lists in a sorted order.

Then, a new linked list is created with the first element of the merged deque as its head. The rest of the elements in the deque are iterated and new nodes are created for each of these elements which are then added to the new linked list in a sorted order.

ALGORITHM:

1.Create a class Node with data, next and prev attributes.
2.Define a function sorted_merge that takes two arguments head1 and head2.
3.Check if either of the linked lists is empty, return the other list.
4.Create two empty deques deque1 and deque2.
5.Traverse both the input linked lists and append their values to the corresponding deque.
6.Create a new deque called merged and merge the two deques by comparing their values one by one.
7.Create a new linked list by popping the values from the merged deque and assigning them to the next attribute of each node.
8Return the head of the merged linked list.

C++




#include <iostream>
#include <deque>
using namespace std;
 
class Node {
public:
    int data;
    Node* next;
    Node* prev;
    Node(int data=0) {
        this->data = data;
        this->next = NULL;
        this->prev = NULL;
    }
};
 
Node* sorted_merge(Node* head1, Node* head2) {
    if (!head1) {
        return head2;
    }
    if (!head2) {
        return head1;
    }
 
    // create a deque for the merged linked list
    deque<int> deque1;
    deque<int> deque2;
 
    // add the nodes from the linked lists to the deques
    Node* node1 = head1;
    Node* node2 = head2;
    while (node1) {
        deque1.push_back(node1->data);
        node1 = node1->next;
        if (node1 == head1) {
            break;
        }
    }
    while (node2) {
        deque2.push_back(node2->data);
        node2 = node2->next;
        if (node2 == head2) {
            break;
        }
    }
 
    // merge the two deques into a new deque
    deque<int> merged;
    while (!deque1.empty() && !deque2.empty()) {
        if (deque1.front() < deque2.front()) {
            merged.push_back(deque1.front());
            deque1.pop_front();
        }
        else {
            merged.push_back(deque2.front());
            deque2.pop_front();
        }
    }
    while (!deque1.empty()) {
        merged.push_back(deque1.front());
        deque1.pop_front();
    }
    while (!deque2.empty()) {
        merged.push_back(deque2.front());
        deque2.pop_front();
    }
 
    // create a new head for the merged linked list
    Node* head = new Node(merged.front());
    merged.pop_front();
    Node* current = head;
 
    // add the remaining nodes to the merged linked list
    while (!merged.empty()) {
        Node* node = new Node(merged.front());
        merged.pop_front();
        current->next = node;
        node->prev = current;
        current = current->next;
    }
 
    // make the linked list circular
    head->prev = current;
    current->next = head;
 
    return head;
}
 
  
  int main() {
    // create the first linked list: 1 <-> 3 <-> 7 <-> 8
    Node* head1 = new Node(1);
    Node* node1 = new Node(3);
    Node* node2 = new Node(7);
    Node* node3 = new Node(8);
    head1->next = node1;
    node1->prev = head1;
    node1->next = node2;
    node2->prev = node1;
    node2->next = node3;
    node3->prev = node2;
    node3->next = head1;
    head1->prev = node3;
 
    // create the second linked list: 2 <-> 5 <-> 9 <-> 11
    Node* head2 = new Node(2);
    node1 = new Node(5);
    node2 = new Node(9);
    node3 = new Node(11);
    head2->next = node1;
    node1->prev = head2;
    node1->next = node2;
    node2->prev = node1;
    node2->next = node3;
    node3->prev = node2;
    node3->next = head2;
    head2->prev = node3;
 
    // merge the two linked lists
    Node* merged = sorted_merge(head1, head2);
 
    // print the merged list
    Node* current = merged;
    do {
        cout << current->data << " <-> ";
        current = current->next;
    } while (current != merged);
    cout << endl;
 
    return 0;
}


Java




import java.util.Deque;
import java.util.LinkedList;
 
class Node {
    int data;
    Node next;
    Node prev;
 
    Node(int data)
    {
        this.data = data;
        this.next = null;
        this.prev = null;
    }
}
 
public class Main {
    public static Node sortedMerge(Node head1, Node head2)
    {
        if (head1 == null) {
            return head2;
        }
        if (head2 == null) {
            return head1;
        }
 
        // create a deque for the merged linked list
        Deque<Integer> deque1 = new LinkedList<>();
        Deque<Integer> deque2 = new LinkedList<>();
 
        // add the nodes from the linked lists to the deques
        Node node1 = head1;
        Node node2 = head2;
        while (node1 != null) {
            deque1.addLast(node1.data);
            node1 = node1.next;
            if (node1 == head1) {
                break;
            }
        }
        while (node2 != null) {
            deque2.addLast(node2.data);
            node2 = node2.next;
            if (node2 == head2) {
                break;
            }
        }
 
        // merge the two deques into a new deque
        Deque<Integer> merged = new LinkedList<>();
        while (!deque1.isEmpty() && !deque2.isEmpty()) {
            if (deque1.getFirst() < deque2.getFirst()) {
                merged.addLast(deque1.removeFirst());
            }
            else {
                merged.addLast(deque2.removeFirst());
            }
        }
        while (!deque1.isEmpty()) {
            merged.addLast(deque1.removeFirst());
        }
        while (!deque2.isEmpty()) {
            merged.addLast(deque2.removeFirst());
        }
 
        // create a new head for the merged linked list
        Node head = new Node(merged.getFirst());
        merged.removeFirst();
        Node current = head;
 
        // add the remaining nodes to the merged linked list
        while (!merged.isEmpty()) {
            Node node = new Node(merged.getFirst());
            merged.removeFirst();
            current.next = node;
            node.prev = current;
            current = current.next;
        }
 
        // make the linked list circular
        head.prev = current;
        current.next = head;
 
        return head;
    }
 
    public static void main(String[] args)
    {
        // create the first linked list: 1 <-> 3 <-> 7 <-> 8
        Node head1 = new Node(1);
        Node node1 = new Node(3);
        Node node2 = new Node(7);
        Node node3 = new Node(8);
        head1.next = node1;
        node1.prev = head1;
        node1.next = node2;
        node2.prev = node1;
        node2.next = node3;
        node3.prev = node2;
        node3.next = head1;
        head1.prev = node3;
 
        // create the second linked list: 2 <-> 5 <-> 9 <->
        // 11
        Node head2 = new Node(2);
        node1 = new Node(5);
        node2 = new Node(9);
        node3 = new Node(11);
        head2.next = node1;
        node1.prev = head2;
        node1.next = node2;
        node2.prev = node1;
        node2.next = node3;
        node3.prev = node2;
        node3.next = head2;
        head2.prev = node3;
 
        // merge the two linked lists
        Node merged = sortedMerge(head1, head2);
 
        // print the merged list
        Node current = merged;
        do {
            System.out.print(current.data + " ");
            current = current.next;
        } while (current != merged);
        System.out.println();
    }
}
 
// This code is contributed by rambabuguphka


Python3




from collections import deque
 
class Node:
    def __init__(self, data=None):
        self.data = data
        self.next = None
        self.prev = None
 
def sorted_merge(head1, head2):
    if not head1:
        return head2
    if not head2:
        return head1
     
    # create a deque for the merged linked list
    deque1 = deque()
    deque2 = deque()
     
    # add the nodes from the linked lists to the deques
    node1 = head1
    node2 = head2
    while node1:
        deque1.append(node1.data)
        node1 = node1.next
        if node1 == head1:
            break
    while node2:
        deque2.append(node2.data)
        node2 = node2.next
        if node2 == head2:
            break
     
    # merge the two deques into a new deque
    merged = deque()
    while deque1 and deque2:
        if deque1[0] < deque2[0]:
            merged.append(deque1.popleft())
        else:
            merged.append(deque2.popleft())
    while deque1:
        merged.append(deque1.popleft())
    while deque2:
        merged.append(deque2.popleft())
     
    # create a new head for the merged linked list
    head = Node(merged.popleft())
    current = head
     
    # add the remaining nodes to the merged linked list
    while merged:
        node = Node(merged.popleft())
        current.next = node
        node.prev = current
        current = current.next
     
    # make the linked list circular
    head.prev = current
    current.next = head
     
    return head
# create the first linked list: 1 <-> 3 <-> 7 <-> 8
head1 = Node(1)
node1 = Node(3)
node2 = Node(7)
node3 = Node(8)
head1.next = node1
node1.prev = head1
node1.next = node2
node2.prev = node1
node2.next = node3
node3.prev = node2
node3.next = head1
head1.prev = node3
 
# create the second linked list: 2 <-> 5 <-> 9 <-> 11
head2 = Node(2)
node1 = Node(5)
node2 = Node(9)
node3 = Node(11)
head2.next = node1
node1.prev = head2
node1.next = node2
node2.prev = node1
node2.next = node3
node3.prev = node2
node3.next = head2
head2.prev = node3
 
# merge the two linked lists
merged_head = sorted_merge(head1, head2)
 
# print the sorted linked list
node = merged_head
while True:
    print(node.data, end=' ')
    node = node.next
    if node == merged_head:
        break


C#




using System;
using System.Collections.Generic;
public class Node
{
    public int data;
    public Node next;
    public Node prev;
 
    public Node(int data = 0)
    {
        this.data = data;
        this.next = null;
        this.prev = null;
    }
}
 
 
public class SortedMerge
{
    static Node SortedMergeNodes(Node head1, Node head2)
    {
        if (head1 == null)
        {
            return head2;
        }
        if (head2 == null)
        {
            return head1;
        }
 
        // create a deque for the merged linked list
        var deque1 = new LinkedList<int>();
        var deque2 = new LinkedList<int>();
 
        // add the nodes from the linked lists to the deques
        Node node1 = head1;
        Node node2 = head2;
        while (node1 != null)
        {
            deque1.AddLast(node1.data);
            node1 = node1.next;
            if (node1 == head1)
            {
                break;
            }
        }
        while (node2 != null)
        {
            deque2.AddLast(node2.data);
            node2 = node2.next;
            if (node2 == head2)
            {
                break;
            }
        }
 
        // merge the two deques into a new deque
        var merged = new LinkedList<int>();
        while (deque1.Count > 0 && deque2.Count > 0)
        {
            if (deque1.First.Value < deque2.First.Value)
            {
                merged.AddLast(deque1.First.Value);
                deque1.RemoveFirst();
            }
            else
            {
                merged.AddLast(deque2.First.Value);
                deque2.RemoveFirst();
            }
        }
        while (deque1.Count > 0)
        {
            merged.AddLast(deque1.First.Value);
            deque1.RemoveFirst();
        }
        while (deque2.Count > 0)
        {
            merged.AddLast(deque2.First.Value);
            deque2.RemoveFirst();
        }
 
        // create a new head for the merged linked list
        var head = new Node(merged.First.Value);
        merged.RemoveFirst();
        var current = head;
 
        // add the remaining nodes to the merged linked list
        while (merged.Count > 0)
        {
            var node = new Node(merged.First.Value);
            merged.RemoveFirst();
            current.next = node;
            node.prev = current;
            current = current.next;
        }
 
        // make the linked list circular
        head.prev = current;
        current.next = head;
 
        return head;
    }
 
    public static void Main(string[] args)
    {
        // create the first linked list: 1 <-> 3 <-> 7 <-> 8
        Node head1 = new Node(1);
        Node node1 = new Node(3);
        Node node2 = new Node(7);
        Node node3 = new Node(8);
        head1.next = node1;
        node1.prev = head1;
        node1.next = node2;
        node2.prev = node1;
        node2.next = node3;
        node3.prev = node2;
        node3.next = head1;
        head1.prev = node3;
 
        // create the second linked list: 2 <-> 5 <-> 9 <-> 11
        Node head2 = new Node(2);
        node1 = new Node(5);
        node2 = new Node(9);
        node3 = new Node(11);
        head2.next = node1;
        node1.prev = head2;
        node1.next = node2;
        node2.prev = node1;
        node2.next = node3;
        node3.prev = node2;
        node3.next = head2;
        head2.prev = node3;
 
        // merge the two linked lists
        Node merged = SortedMergeNodes(head1, head2);
 
        // print the merged list
        Node current = merged;
        do
        {
            Console.Write(current.data + " ");
            current = current.next;
        } while (current != merged);
        Console.WriteLine();
    }
}


Javascript




class Node {
    constructor(data = 0) {
        this.data = data;
        this.next = null;
        this.prev = null;
    }
}
 
function sorted_merge(head1, head2) {
    if (!head1) {
        return head2;
    }
    if (!head2) {
        return head1;
    }
 
    // Create an array for the merged linked list
    const deque1 = [];
    const deque2 = [];
 
    // Add the nodes from the linked lists to the arrays
    let node1 = head1;
    let node2 = head2;
    while (node1) {
        deque1.push(node1.data);
        node1 = node1.next;
        if (node1 === head1) {
            break;
        }
    }
    while (node2) {
        deque2.push(node2.data);
        node2 = node2.next;
        if (node2 === head2) {
            break;
        }
    }
 
    // Merge the two arrays into a new array
    const merged = [];
    while (deque1.length > 0 && deque2.length > 0) {
        if (deque1[0] < deque2[0]) {
            merged.push(deque1.shift());
        } else {
            merged.push(deque2.shift());
        }
    }
    while (deque1.length > 0) {
        merged.push(deque1.shift());
    }
    while (deque2.length > 0) {
        merged.push(deque2.shift());
    }
 
    // Create a new head for the merged linked list
    const head = new Node(merged[0]);
    merged.shift();
    let current = head;
 
    // Add the remaining nodes to the merged linked list
    merged.forEach(data => {
        const node = new Node(data);
        current.next = node;
        node.prev = current;
        current = current.next;
    });
 
    // Make the linked list circular
    head.prev = current;
    current.next = head;
 
    return head;
}
 
// Same main function in JavaScript
function main() {
    // Create the first linked list: 1 <-> 3 <-> 7 <-> 8
    const head1 = new Node(1);
    let node1 = new Node(3);
    let node2 = new Node(7);
    let node3 = new Node(8);
    head1.next = node1;
    node1.prev = head1;
    node1.next = node2;
    node2.prev = node1;
    node2.next = node3;
    node3.prev = node2;
    node3.next = head1;
    head1.prev = node3;
 
    // Create the second linked list: 2 <-> 5 <-> 9 <-> 11
    const head2 = new Node(2);
    node1 = new Node(5);
    node2 = new Node(9);
    node3 = new Node(11);
    head2.next = node1;
    node1.prev = head2;
    node1.next = node2;
    node2.prev = node1;
    node2.next = node3;
    node3.prev = node2;
    node3.next = head2;
    head2.prev = node3;
 
    // Merge the two linked lists
    const merged = sorted_merge(head1, head2);
 
    // Print the merged list
    let current = merged;
    do {
        process.stdout.write(current.data + " <-> ");
        current = current.next;
    } while (current !== merged);
    console.log();
}
 
main();


Output

1 2 3 5 7 8 9 11 





The time complexity of this approach is O(N1 + N2), where N1 is the length of the first linked list and N2 is the length of the second linked list

The space complexity of this approach is O(N1 + N2)



Last Updated : 14 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads