C++ merge sort O(nlogn) time and O(1) space


  • 0
    Z

    C++ merge sort

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* sortList(ListNode* head) {
            if(head == NULL || head->next==NULL){return head;}
            ListNode *slow = head;
            ListNode *fast = head;
            ListNode *pre = head;
            while(fast!= NULL && fast->next != NULL){
                pre = slow;
                slow = slow->next;
                fast = fast->next->next;
            }
            pre->next = NULL;
            
            ListNode *head1 = sortList(head);
            ListNode *head2 = sortList(slow);
            
            return merge(head1,head2);
        }
        
        ListNode *merge(ListNode *a1, ListNode *a2){
            ListNode *head = a1->val<a2->val?a1:a2;
            ListNode *p=head;
            if(head == a1)a1=a1->next;
            else a2=a2->next;
            while(a1!=NULL && a2!=NULL){
                if(a1->val < a2->val){
                    p->next = a1;
                    a1=a1->next;
                    p=p->next;
                }
                else{
                    p->next = a2;
                    a2 = a2->next;
                    p=p->next;
                }
            }
            if(a1 == NULL)p->next = a2;
            if(a2 == NULL)p->next = a1;
            return head;
        }
        
    };
    

Log in to reply
 

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