Advertisement
imashutosh51

Merge Sort for Linked List

Oct 16th, 2022 (edited)
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.92 KB | None | 0 0
  1. /**
  2.  * Definition for singly-linked list.
  3.  * struct ListNode {
  4.  *     int val;
  5.  *     ListNode *next;
  6.  *     ListNode() : val(0), next(nullptr) {}
  7.  *     ListNode(int x) : val(x), next(nullptr) {}
  8.  *     ListNode(int x, ListNode *next) : val(x), next(next) {}
  9.  * };
  10.  */
  11. int _len(ListNode* head){
  12.     int ans=0;
  13.     while(head){head=head->next; ans++;}
  14.     return ans;
  15. }
  16. ListNode* find_mid(ListNode *head){
  17.     int half=_len(head)/2; if(half>0)half--;  //reducing half by one so it send just before the middle
  18.     ListNode *mid=head;                       //node
  19.     while(half--){
  20.         mid=mid->next;
  21.     }
  22.     return mid;
  23. }
  24. ListNode *merge(ListNode *head,ListNode *mid){
  25.    
  26.     if(!head) return mid;
  27.     if(!mid) return head;
  28.     ListNode *root;
  29.     if(head->val<mid->val){ root=new ListNode(head->val);head=head->next;}
  30.     else{ root=new ListNode(mid->val);mid=mid->next;}
  31.     ListNode *cur=root;
  32.     while(head && mid){
  33.         if(head->val<mid->val){ cur->next=new ListNode(head->val);cur=cur->next; head=head->next;}
  34.         else{ cur->next=new ListNode(mid->val);cur=cur->next;mid=mid->next;}
  35.     }
  36.     while(head){
  37.         cur->next=new ListNode(head->val);cur=cur->next;head=head->next;
  38.     }
  39.     while(mid){
  40.         cur->next=new ListNode(mid->val);cur=cur->next;mid=mid->next;
  41.     }
  42.     return root;
  43. }
  44. ListNode* mergesort(ListNode* head){
  45.     if(!(head->next)) return head;  //If only one node,return the node
  46.     ListNode *temp=find_mid(head);  //temp is having node just before mid node so that we can break
  47.     ListNode *mid=temp->next;  //mid node
  48.     temp->next=NULL;  //breaking the linked list into two halves(one might be bigger in odd case)
  49.     head=mergesort(head);
  50.     mid=mergesort(mid);
  51.     ListNode *ans=merge(head,mid);
  52.  
  53.     return ans;
  54. }
  55. class Solution {
  56. public:
  57.     ListNode* sortList(ListNode* head) {
  58.         if(!head) return head;
  59.         return mergesort(head);
  60.     }
  61. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement