Merge Sort on Doubly Linked List | Practice | GeeksforGeeks

Given Pointer/Reference to the head of a doubly linked list of N nodes, the task is to Sort the given doubly linked list using Merge Sort in both non-decreasing and non-increasing order.
Example 1:
Input:
N = 8
value[] = {7,3,5,2,6,4,1,8}
Output:
1 2 3 4 5 6 7 8
8 7 6 5 4 3 2 1
Explanation: After sorting the given
linked list in both ways, resultant
matrix will be as given in the first
two line of output, where first line
is the output for non-decreasing
order and next line is for non-
increasing order.

Example 2:
Input:
N = 5
value[] = {9,15,0,-1,0}
Output:
-1 0 0 9 15
15 9 0 0 -1
Explanation: After sorting the given
linked list in both ways, the
resultant list will be -1 0 0 9 15
in non-decreasing order and 
15 9 0 0 -1 in non-increasing order.
Your Task:
The task is to complete the function sortDoubly() which sorts the doubly linked list. The printing is done automatically by the driver code.
Constraints:
1 <= N <= 105
0
annanyamathur2 weeks ago
struct Node* merge(struct Node *left,  struct Node *right)
{
    if(!left) return right;
    if(!right) return left;
    struct Node *curr1=left , *curr2=right,*temp=new Node(-1), *a=temp;
    
    while(curr1 && curr2)
    {
        if(curr1->data<curr2->data)
        {
           a->next=curr1;
           curr1->prev=a;
            a=a->next;
            curr1=curr1->next;
        }
        else
        {
            a->next=curr2;
           curr2->prev=a;
            a=a->next;
            curr2=curr2->next;
        }
    }
    while(curr1)
    {
        a->next=curr1;
           curr1->prev=a;
            a=a->next;
            curr1=curr1->next;
    }
    while(curr2)
    {
         a->next=curr2;
           curr2->prev=a;
            a=a->next;
            curr2=curr2->next;
    }
    a->next=NULL;
    temp=temp->next;
    
    temp->prev=NULL;
    return temp;
}
struct Node *findMid(struct Node*head , struct Node *tail)
{
    struct Node *slow=head, *fast=head;
    while(fast!=tail && fast->next!=tail)
    {
        slow=slow->next;
        fast=fast->next->next;
    }
    return slow;
}
struct Node *mergeSort(struct Node*head , struct Node *tail)
{
    if(head==tail)
    return new Node(head->data);
    Node *mid=findMid(head,tail);
    Node *left=mergeSort(head,mid);
    Node *right=mergeSort(mid->next,tail);
    Node *res=merge(left,right);
    return res;
}
struct Node *sortDoubly(struct Node *head)
{
    Node *tail=head;
    while(tail->next!=NULL)
    {
        tail=tail->next;
    }
    return mergeSort(head,tail);
}

0
tarunkanade1 month ago
3.1/6.0
static Node sortDoubly(Node head)
    {
        // add your code here
        if(head.next == null){
            return head;
        }
        
        Node slow = head, fast = head;
        
        while(fast.next != null && fast.next.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }
        
        Node secondHead = slow.next;
        slow.next = null;
        secondHead.prev = null;
        
        Node first = sortDoubly(head);
        Node second = sortDoubly(secondHead);
        return merge(first, second);
    }
    
    private static Node merge(Node first, Node second){
        Node head;
        
        if(first.data <= second.data){
            head = first;
            first = first.next;
        }else{
            head = second;
            second = second.next;
        }
        
        Node cur = head;
        
        while(first != null && second != null){
            if(first.data <= second.data){
                cur.next = first;
                first.prev = cur;
                first = first.next;
            }else{
                cur.next = second;
                second.prev = cur;
                second = second.next;
            }
            
            cur = cur.next;
        }
        
        while(first != null){
            cur.next = first;
            first.prev = cur;
            first = first.next;
            cur = cur.next;
        }
        
        while(second != null){
            cur.next = second;
            second.prev = cur;
            second = second.next;
            cur = cur.next;
        }
        
        cur.next = null;
        
        return head;
    }
0
surabhichoubey552 months ago
ALGO
1. FIND THE MID OF THE DLL
2. THE NODE AFTER MID STORE IN TEMPRARY POINTER
3 DO NULL AFTER THE MID NODE
4 CALL THE RECURSION ON START TO MID AGAIN CALL THE RECURSION MID TO END
5 MERGE TWO SORTED LL AND RETURN NEWHEAD
 
 
struct Node *mergeDLL(struct Node *head1 ,struct Node *head2){   struct Node *newhead = NULL;   struct Node *newtail = NULL;   while(head1!=NULL && head2!=NULL )   {       if(newhead == NULL)       {           if(head1->data<head2->data)           {               newhead = head1;               newtail = head1;               head1 = head1->next;           }           else           {               newhead = head2;               newtail = head2;               head2 = head2->next;           }       }       else       {           if(head1->data<head2->data)           {               newtail->next = head1;               head1->prev = newtail;               newtail = head1;               head1 = head1->next;           }           else           {               newtail->next = head2;               head2->prev = newtail;               newtail = head2;               head2 = head2->next;                          }       }   }   while(head1!=NULL)   {              newtail->next = head1;               head1->prev = newtail;               newtail = head1;               head1 = head1->next;   }   while(head2!=NULL)   {               newtail->next = head2;               head2->prev = newtail;               newtail = head2;               head2 = head2->next;   }   return newhead;}struct Node *sortDoubly(struct Node *head){// Your code hereif(head == NULL || head->next == NULL){    return head;}struct Node *slow = head;struct Node *fast = head;while(fast->next!=NULL&&fast->next->next!=NULL){    slow = slow->next;    fast = fast->next->next;}struct Node *afterMid = slow->next;slow->next->prev = NULL;slow->next = NULL;struct Node *head1 =  sortDoubly (head);struct Node *head2 =  sortDoubly(afterMid);struct Node *ans = mergeDLL(head1,head2);return ans;
} 
0
zakarian17s2 months ago
struct Node* merge(Node* head, Node* tmp){
    Node* nw,*n1,*n2;
    if(head->data>tmp->data){
        nw = new Node(tmp->data);
        n1 = head, n2 = tmp->next;
    }else{
        nw = new Node(head->data);
        n1 = head->next, n2 = tmp;
    }
    Node* nx = nw;
    while(n1 && n2){
        if(n1->data<n2->data){
            Node* k = new Node(n1->data);
            n1 = n1->next;
            k->prev = nx;
            nx->next = k;
        }else{
            Node* k = new Node(n2->data);
            n2 = n2->next;
            k->prev = nx;
            nx->next = k;
        }
        nx = nx->next;
    }
    if(n1){
        nx->next = n1;
        n1->prev = nx;
    }
    if(n2){
        nx->next = n2;
        n2->prev = nx;
    }
    return nw;
}

struct Node* split(Node* head){
    if(!head->next) return head;
    Node* slo = head, *fa = head->next;
    while(fa && fa->next){
        slo = slo->next;
        fa = fa->next;
        if(fa) fa = fa->next;
    }
    
    Node* tmp = slo->next;
    slo->next = NULL;
    tmp->prev = NULL;
    
    // return head;
    
    head = split(head);
    tmp = split(tmp);
    
    return merge(head,tmp);
}

//Function to sort the given doubly linked list using Merge Sort.
struct Node *sortDoubly(struct Node *head)
{
    if(!head) return NULL;
    return split(head);
	
}
0
yashkotalwar103 months ago
// Java       ArrayList<Integer> list = new ArrayList<Integer>();       Node currentNode = head;       while (currentNode != null){           list.add(currentNode.data);           currentNode = currentNode.next;       }       Collections.sort(list);       Node current2 = head;       int n = list.size();       for (int j= n-1; j>=0;j--){           current2.data = list.get(j);           current2 = current2.next;       }       Node current = head; int i=0;       while (current != null){           current.data = list.get(i);           current = current.next;           i++;       }       return head;
0
subhammahanta183 months ago
//Java Cheat code ;)
class LinkedList{   //Function to sort the given doubly linked list using Merge Sort.   static Node sortDoubly(Node head)   {       int count=0;        Node curr=head;        while(curr!=null)        {            count++;            curr=curr.next;        }        int a[]=new int[count];        curr=head;        for(int i=0;i<a.length;i++)        {            a[i]=curr.data;            curr=curr.next;        }        Arrays.sort(a);                curr=head;          for(int i=0;i<a.length;i++)        {           curr.data=a[i];           curr=curr.next;        }                return head;           }}
0
007msr0073 months ago
// Middile pointer
struct Node *getmiddile(struct Node *head)
{
    Node *slow = head, *fast = head;
    Node *mid=NULL;
    while(fast->next!=NULL && fast->next->next != NULL)
    {
        slow = slow->next;
        fast = fast->next->next;
    }
    mid = slow->next;
    slow->next->prev = NULL;
    slow->next = NULL;
    return mid;
}
//Merge two sorted doubly Linkedlist
struct Node *merge(struct Node *head1,struct Node *head2)
{
    Node *tail=NULL,*head=NULL;
    if(head1->data>=head2->data)
    {
        head = tail = head2;
        head2 = head2->next;
    }
    else
    {
         head = tail = head1;
        head1 = head1->next;
    }
    while(head1!=NULL && head2!=NULL)
    {
         if(head1->data<=head2->data)
         {
             tail->next = head1;
             head1->prev = tail;
             tail = tail->next;
             head1 = head1->next;
            
         }
         else
         {
             tail->next = head2;
             head2->prev = tail;
             tail = tail->next;
             head2 = head2->next;
             
         }
    }
    if(head1==NULL)
    {
        tail->next = head2;
        head2->prev = tail;
    }
    else
    {
        tail->next = head1;
        head1->prev = tail;
    }
 return head;
}

// Mergesort function 
struct Node *mergesort(struct Node *head)
{
    if(head==NULL || head->next==NULL)
      return head ;
    Node *mid = getmiddile(head);
    Node *left = mergesort(head);
    Node *right = mergesort(mid);
    return merge(left,right);
}

//Function to sort the given doubly linked list using Merge Sort.
struct Node *sortDoubly(struct Node *head)
{
	// Your code here
	return mergesort(head);
	
}
0
enjoyboy2225 months ago
Total Time Taken:
3.4/6.0
 
 static Node sortDoubly(Node head)   {       ArrayList<Integer> arr = new ArrayList<>();       Node curr = head;       while(curr != null){           arr.add(curr.data);           curr = curr.next;       }       Collections.sort(arr);       Node finalhead = null;       Node currtail = new Node((int)arr.get(0));       finalhead = currtail;       finalhead.prev = null;       Iterator itr = arr.iterator();       boolean firsttime = true;       while(itr.hasNext()){           if(firsttime){               firsttime = false;               int data = (int)itr.next();           }           else{                          Node temp = new Node((int)itr.next());           currtail.next = temp;           temp.prev = currtail;            currtail = temp;           }       }       return finalhead;   }
 
0
kskhalife965 months ago
Node* merge(Node* firstHalf, Node* secondHalf) 
    {
        Node* newHead = new Node(0);
        Node* currPtr = newHead;
        
        while (firstHalf != nullptr && secondHalf != nullptr) 
        {
            if (firstHalf->data < secondHalf->data)
            {
                currPtr->data = firstHalf->data;
                firstHalf = firstHalf->next;
                if (firstHalf == nullptr)
                {
                    while (secondHalf != nullptr)
                    {
                        currPtr->next = new Node(secondHalf->data);
                        (currPtr->next)->prev = currPtr; 
                        currPtr = currPtr->next;
                        secondHalf = secondHalf->next;
                    }
                }
                else 
                {
                    currPtr->next = new Node(0);
                    (currPtr->next)->prev = currPtr;
                    currPtr = currPtr->next;
                }
            }
            else 
            {
                currPtr->data = secondHalf->data;
                secondHalf = secondHalf->next;
                if (secondHalf == nullptr)
                {
                    while (firstHalf != nullptr)
                    {
                        currPtr->next = new Node(firstHalf->data);
                        (currPtr->next)->prev = currPtr;
                        currPtr = currPtr->next;
                        firstHalf = firstHalf->next;
                    }
                }
                else 
                {
                    currPtr->next = new Node(0);
                    (currPtr->next)->prev = currPtr;
                    currPtr = currPtr->next;
                }
            }
        }
        return newHead;
    }

struct Node *sortDoubly(struct Node *head)
{
    if (head->next == nullptr) return head;
        
        int count = 2;
        Node* tail = head->next;
        Node* middle = head;
       
        while (tail->next != nullptr) 
        {
            count++;
            tail = tail->next;
            if (tail->next != nullptr && count % 2 == 1)
                middle = middle->next;
        }
        
        Node* secondHead = middle->next;
        middle->next = nullptr;
        
        if (count == 2) 
        { 
            head->next = nullptr;
            secondHead->next = nullptr;
        }
        
        Node* firstHalf = sortDoubly(head);
        Node* secondHalf = sortDoubly(secondHead);
        Node* newHead = merge(firstHalf, secondHalf);
        return newHead;
}
+1
ketankumar17 months ago
C++ Solution:
Node *findMid(Node *head) {
    if(head == NULL and head->next == NULL) return head;
    
    Node *fastptr = head;
    Node *slowptr = head;
    
    while(fastptr and fastptr->next) {
        fastptr = fastptr->next->next;
        if(fastptr) slowptr = slowptr->next;
    }
    
    return slowptr;
}


Node *merge(Node *head1, Node *head2) {
    
    if(!head1) return head2;
    if(!head2) return head1;
    
    
    Node *reshead = NULL;
    Node *curr = NULL;
    
    Node *ptr1 = head1;
    Node *ptr2 = head2;
    
    while(ptr1 and ptr2) {
        
        if(ptr1->data <= ptr2->data) {
            
            if(!reshead) {
                reshead = ptr1;
                curr = ptr1;
            }
            
            else {
                curr->next = ptr1;
                ptr1->prev = curr;
                curr = curr->next;
            }
            
            ptr1 = ptr1->next;
        }
        
        else {
            
            if(!reshead) {
                reshead = ptr2;
                curr = ptr2;
            }
            
            else {
                curr->next = ptr2;
                ptr2->prev = curr;
                curr = curr->next;
            }
            
            ptr2 = ptr2->next;            
        }
    }
    
    while(ptr1) {

        curr->next = ptr1;
        ptr1->prev = curr;
        curr = curr->next;
        ptr1 = ptr1->next;
        
    }
    
    while(ptr2) {

        curr->next = ptr2;
        ptr2->prev = curr;
        curr = curr->next;
        ptr2 = ptr2->next;
        
    }
    
    if(!ptr1 and !ptr2) curr->next = NULL;
    
    return reshead;
    
}

//Function to sort the given doubly linked list using Merge Sort.
struct Node *sortDoubly(struct Node *head)
{
	// Your code here
	
	if(head and !head->next) return head;
	
	if(head and head->next) {
	    
	    Node *mid = findMid(head);
	    Node *head1 = (mid != NULL)?(mid->next):NULL;
	    mid->next = NULL;
	    head1->prev = NULL;
	    
	    head = sortDoubly(head);
	    head1 = sortDoubly(head1);
	    
	    return merge(head,head1);
	}
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.