Merge Sort for Linked List | Practice | GeeksforGeeks

Given Pointer/Reference to the head of the linked list, the task is to Sort the given linked list using Merge Sort.
Note: If the length of linked list is odd, then the extra node should go in the first list while splitting.
Example 1:
Input:
N = 5
value[]  = {3,5,2,4,1}
Output: 1 2 3 4 5
Explanation: After sorting the given
linked list, the resultant matrix
will be 1->2->3->4->5.

Example 2:
Input:
N = 3
value[]  = {9,15,0}
Output: 0 9 15
Explanation: After sorting the given
linked list , resultant will be
0->9->15.
Your Task:
For C++ and Python: The task is to complete the function mergeSort() which sort the linked list using merge sort function.
For Java: The task is to complete the function mergeSort() and return the node which can be used to print the sorted linked list.
Expected Time Complexity: O(N*Log(N))
Expected Auxiliary Space: O(N)
Constraints:
1 <= T <= 100
1 <= N <= 105
 
0
sandeep55213 days ago
C++ Merge Sort Solution
Node* mergeTwoLists(Node* l1, Node* l2) {
       Node *d= new Node(0);
       auto p=d;
       while(l1 and l2){
           if(l1->data<l2->data){
               p->next=l1;
               l1=l1->next;
           }
           else{
               p->next=l2;
               l2=l2->next;
           }
           p=p->next;
       }
       if(l1) p->next=l1;
       else p->next=l2;
       return d->next;
   }
   Node* mergeSort(Node* head) {
       // your code here
       if(!head or !(head->next)) return head;
       Node *slow=head;
       Node *fast=head;
       Node *tmp=NULL;
       while(fast and fast->next){
           tmp=slow;
           slow=slow->next;
           fast=fast->next->next;
       }
       tmp->next=NULL;
       Node* f = mergeSort(head);
       Node* s = mergeSort(slow);
       return mergeTwoLists(f,s);
   }
+2
shakshamkaushik11 week ago
 
class Solution{   //Function to sort the given linked list using Merge Sort.   static Node mergeSort(Node head)   {       if(head == null || head.next == null){           return head;       }       Node middle = getMiddle(head);                     Node part1 = head;       Node part2 = middle.next;       middle.next = null;       part1 = mergeSort(part1);             part2 = mergeSort(part2);       head = merge(part1,part2);       return head;         }   static Node getMiddle(Node head){       Node slow = head;       Node fast = head;       while(fast.next!=null && fast.next.next!=null){           slow = slow.next;           fast = fast.next.next;       }       return slow;   }  static Node merge(Node h1, Node h2){      if(h1 == null){          return h2;      }      if(h2 == null){          return h1;      }
       Node head,tail;       if(h1.data<=h2.data){           head = h1;           tail = h1;           h1 = h1.next;                  }else{           head = h2;           tail = h2;           h2 = h2.next;       }       while (h1!=null && h2!=null){           if(h1.data<= h2.data){               tail.next = h1;               h1 = h1.next;               tail = tail.next;           }else{               tail.next = h2;               h2 = h2.next;               tail = tail.next;       }       }       if(h1!=null){           tail.next = h1;       }else{           tail.next = h2;       }   
return head;}}
 
0
nakulgopal2 weeks ago
Very simple and intuitive approach C++.

class Solution{
  public:
    //Function to sort the given linked list using Merge Sort.
    Node* getMid(Node* head){
        Node* slow = head;
        Node* fast = head->next;
        
        while(fast!=nullptr and fast->next!=nullptr){
            slow = slow->next;
            fast = fast->next->next;
        }
        return slow;
    }
    
    Node* merge(Node*l,Node*r){
        Node* newList = new Node(-1);
        Node* ans = newList;
        while(l!=nullptr and r!=nullptr){
            if(l->data<r->data){
                    ans->next = new Node(l->data);
                    ans = ans->next;
                    l = l->next;
            }else{
                 ans->next = new Node(r->data);
                    ans = ans->next;
                    r= r->next;
            }
        }
        
        while(l!=nullptr){
          ans->next = new Node(l->data);
                    ans = ans->next;
                    l = l->next;
        }
         while(r!=nullptr){
            ans->next = new Node(r->data);
                    ans = ans->next;
                    r= r->next;
        }
        return newList->next;
    }
    
    
    Node* mergeSort(Node* head) {
      Node* ans = head;
        if(head->next!=nullptr){
            
            Node* mid  = getMid(head);
            Node* right  = mid->next;
            mid->next = nullptr;
            Node* l = mergeSort(head);
            Node* r = mergeSort(right);
            ans =  merge(l,r);
           
        }
        
        return ans;
    }
};

0
annanyamathur2 weeks ago
Node *merge(Node *left, Node *right) {     Node *curr1=left, *curr2=right, *a=new Node(-1),*temp=a;     while(curr1!=NULL && curr2!=NULL)     {         if(curr1->data<curr2->data)         {             temp->next=curr1;             curr1=curr1->next;             temp=temp->next;         }         else         {              temp->next=curr2;             curr2=curr2->next;             temp=temp->next;         }     }     while(curr1!=NULL)     {          temp->next=curr1;             curr1=curr1->next;             temp=temp->next;     }     while(curr2!=NULL)     {          temp->next=curr2;             curr2=curr2->next;             temp=temp->next;     }     a=a->next;     temp->next=NULL;     return a; }   Node* findmid(Node* head, Node*tail)   {       Node* slow=head, *fast=head;       while(fast!=tail && fast->next!=tail)       {           slow=slow->next;           fast=fast->next->next;       }       return slow;   }   Node* msort(Node *head, Node *tail)   {       if(head==tail)       {           return new Node(head->data);       }       Node *mid=findmid(head,tail);       Node *left=msort(head,mid);       Node *right=msort(mid->next,tail);              Node *root=merge(left,right);       return root;   }   Node* mergeSort(Node* head) {      Node *curr=head;      while(curr->next!=NULL)      {          curr=curr->next;      }     Node *res= msort(head,curr);     return res;   }
0
harshscode3 weeks ago
very easy c++...
 
void mergesorting(Node **head)   {       Node *cur=*head;       Node *first;       Node *second;              if(!cur or !cur->next)       return;              findmiddle(cur,&first,&second);              mergesorting(&first);       mergesorting(&second);       *head=mergeboth(first,second);                 }         Node *mergeboth(Node *first,Node *second)   {       Node *ans=NULL;              if(!first)       return second;       else if(!second)       return first;              if(first->data<second->data)       {           ans=first;           ans->next=mergeboth(first->next,second);       }       else       {           ans=second;           ans->next=mergeboth(first,second->next);       }              return ans;   }   void findmiddle(Node *cur,Node **first,Node **second)   {              Node *fast=cur->next;       Node *slow=cur;       while(fast and fast->next)       {           slow=slow->next;           fast=fast->next->next;                  }              *first=cur;       *second=slow->next;       slow->next=NULL;   }   Node* mergeSort(Node* head) {       mergesorting(&head);       return head;   }
0
himanshukug19cs3 weeks ago
java solution
 
 static Node merge(Node node1, Node node2)   {// Your code hereNode  head =null;Node pre=null;if(node1==null&&node2==null)    return null;else if(node1==null&&node2!=null)     return node2;else if(node1!=null&&node2==null)     return node2;    if(node1.data<=node2.data){    head = new Node(node1.data);    pre=head;    node1=node1.next;}else{    head = new Node(node2.data);    node2=node2.next;    pre=head;}
while(node1!=null&&node2!=null){    if(node1.data<=node2.data){        Node nod= new Node(node1.data);        pre.next=nod;        pre=pre.next;        node1=node1.next;            }    else{         Node nod= new Node(node2.data);         pre.next=nod;        pre=pre.next;         node2=node2.next;    }}if(node1!=null){    while(node1!=null){         Node nod= new Node(node1.data);         pre.next=nod;        pre=pre.next;         node1=node1.next;           }}if(node2!=null){     while(node2!=null){          Node nod= new Node(node2.data);         pre.next=nod;        pre=pre.next;            node2=node2.next;            }}return head;   }   static Node findmiddle(Node head){        Node slow=head;       Node fast=head.next;       while(fast!=null&&fast.next!=null){           fast=fast.next.next;           slow=slow.next;       }       return slow;   }   static Node mergeSort(Node head)   {       // add your code here       if(head==null||head.next==null)           return head;                    Node left=head;       Node mid=findmiddle(head);       Node right=mid.next;       mid.next=null;        Node a1=mergeSort(left);        Node a2=mergeSort(right);       return merge(a1,a2);                   }
0
bheniavedant4 weeks ago
what is wrong with this python code
def sorted(self,x,y):       if x and y:           if x.data > y.data:               x, y = y, x           x.next = self.sorted(x.next,y)       return x,y       def getmiddle(self,head):       if head == None:           return head       slow = head       fast = head       while fast.next and fast.next.next:           slow = slow.next           fast = fast.next.next       return slow          def mergeSort(self, head):       if head is None or head.next is None:           return head       middle = self.getmiddle(head)       next_to_middle = middle.next       middle.next = None       left = self.mergeSort(head)       right = self.mergeSort(next_to_middle)              sortedlst = self.sorted(left,right)       return sortedlst       
+1
shubham211019974 weeks ago
static Node merge(Node h1,Node h2){              if(h1==null) return h2;       if(h2==null) return h1;              Node head,tail;       if(h1.data<=h2.data)  {           head=h1;           tail=h1;           h1=h1.next;       }       else {           head=h2;           tail=h2;           h2=h2.next;       }       while(h1!=null && h2!=null){           if(h1.data<=h2.data){               tail.next=h1;               h1=h1.next;               tail=tail.next;           }else{               tail.next=h2;               h2=h2.next;               tail=tail.next;           }       }       if(h1!=null) tail.next=h1;       else  tail.next=h2;              return head;                 }   static Node middle(Node head){       Node slow=head,fast=head;       while(fast.next!=null && fast.next.next!=null){           slow=slow.next;           fast=fast.next.next;       }       return slow;   }   //Function to sort the given linked list using Merge Sort.   static Node mergeSort(Node head)   {      if(head==null || head.next==null) return head;      Node mid=middle(head);      Node part1=head;      Node part2=mid.next;      mid.next=null;            part1=mergeSort(part1);      part2=mergeSort(part2);            head=merge(part1,part2);      return head;   }
-8
sikkusaurav1231 month ago
simple But not using merg_sort , But test case pass 100/100
 
 Node* mergeSort(Node* head) {       // your code here       Node *p=head;       vector<int>v;       while(p!=NULL)       {         v.push_back(p->data);          p=p->next;       }       sort(v.begin(),v.end());       int i=0;       p=head;       while(p!=NULL)       {           p->data=v[i];           p=p->next;           i++;       }       return head;   }
0
rmn51241 month ago
// for O(1) space
  // we will apply merge sort algorithm
class Solution{
 public:
 // find mid in the linked list
   Node* findMid(Node* head)
   {
       Node* slow = head;
       Node* fast = head->next;
       while(fast!=NULL && fast->next!=NULL)
       {
           fast = fast->next->next;
           slow = slow->next;
       }
       return slow;
   }
   
   // merge sort algorithm 
   Node* merge(Node* left,Node* right)
   {
       Node* ans = new Node(-1);
       Node* temp = ans;
       if(left==NULL)
       {
           return right;
       }
       if(right==NULL)
       {
           return left;
       }
       while(left!=NULL && right!=NULL)
       {
           if(left->data < right->data)
           {
               temp->next = left;
               temp = left;
               left = left->next;
           }
           else{
               temp->next = right;
               temp = right;
               right = right->next;
           }
       }
       while(left!=NULL)
       {
           temp->next = left;
           temp = left;
           left = left->next;
       }
       while(right!=NULL)
       {
           temp->next = right;
           temp = right;
           right = right->next;
       }
       ans = ans->next;
       return ans;
   } 
  
   //Function to sort the given linked list using Merge Sort.
   Node* mergeSort(Node* head) {
    if(head == NULL || head->next == NULL)
    {
        return head;
    }
    Node* left = head;
    Node* mid = findMid(head);
    Node* right = mid->next;
    mid->next = NULL;
    
    left = mergeSort(left);  // sort left half
    right = mergeSort(right); // sort right half
    
    Node* result = merge(left,right);  // apply merge function
    return result;
   }
};

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.