My recursive merge-sort cpp code


  • 0
    C
    class Solution {
    public:
        ListNode* findCenter(ListNode* head)
        {
            if(!head || !head->next) return head;
            
            ListNode* slow = head;
            ListNode* fast = head->next->next;
            
            while(fast)
            {
                slow = slow->next;
                fast = fast->next;
                if(fast) fast = fast->next;
            }
            
            ListNode* center = slow->next;
            slow->next = NULL;
            return center;
        }
        
        ListNode* merge(ListNode* l1, ListNode* l2)
        {
            ListNode fakeHead(0);
            ListNode* ptr = &fakeHead;
            
            while(l1 && l2)
            {
                if(l1->val < l2->val)
                {
                    ptr->next = l1;
                    l1 = l1->next;
                }
                else
                {
                    ptr->next = l2;
                    l2 = l2->next;
                }
                ptr = ptr->next;
            }
            
            if(l1) ptr->next = l1;
            else ptr->next = l2;
            
            return fakeHead.next;
        }
        
        ListNode* sortHelper(ListNode* head)
        {
            if(!head || !head->next) return head;
            
            ListNode* center = findCenter(head);
            
            ListNode* l = sortHelper(head);
            ListNode* r = sortHelper(center);
            
            return merge(l, r);
        }
    
        ListNode* sortList(ListNode* head) 
        {
            return sortHelper(head);
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.