knakul853

Untitled

Jun 17th, 2020
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.25 KB | None | 0 0
  1. /**
  2. knakul853
  3.  */
  4. class Solution {
  5. public:
  6.     ListNode* sortList(ListNode* head) {
  7.        
  8.         // merge sort techniqueue
  9.        
  10.         if(!head || !head->next)return head;
  11.        
  12.         ListNode* slow = head;
  13.         ListNode* fast = head;
  14.         ListNode* tail = slow;
  15.        
  16.         while( fast && fast->next )
  17.         {
  18.             tail = slow;
  19.             fast = fast->next->next;
  20.             slow = slow->next;
  21.         }
  22.         tail->next = NULL;
  23.        
  24.         ListNode* left = sortList(head);
  25.         ListNode* right = sortList(slow);
  26.         return merge(left, right);  
  27.     }
  28.    
  29.     ListNode* merge( ListNode* h1, ListNode* h2 )
  30.     {
  31.         ListNode* dummy = new ListNode(0);
  32.         ListNode* ans = dummy;
  33.        
  34.         while( h1 && h2 )
  35.         {
  36.             if( h1->val < h2->val )
  37.             {
  38.                 dummy->next = new ListNode(h1->val);
  39.                 h1 = h1->next;
  40.                 dummy = dummy->next;
  41.             }
  42.             else{
  43.                  dummy->next = new ListNode(h2->val);
  44.                 h2 = h2->next;
  45.                 dummy = dummy->next;
  46.             }
  47.         }
  48.        
  49.         dummy->next = h1 ? h1 : h2;
  50.        
  51.         return ans->next;  
  52.     }
  53.    
  54. };
Add Comment
Please, Sign In to add comment