148. Sort List

1.問題

  • 排序, 時間複雜度為O(n logn), 空間複雜度為constant

2.想法

  • Divide and conquer, Binary sort

    • 將List分為前後兩段並排序

3.程式碼

/**
 * 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 || !head->next) {
            return head;
        }
        
        //Split the list
        ListNode* prev = NULL;
        ListNode* firstHalf = head;
        ListNode* secondHalf = head;
        while (secondHalf && secondHalf->next) {
            prev = firstHalf;
            firstHalf = firstHalf->next;
            secondHalf = secondHalf->next->next;
        }
        
        //The head of the scend half one
        ListNode* mid = firstHalf;
        prev->next = NULL;
        
        //Divid and conquer
        ListNode* l = sortList(head);
        ListNode* r = sortList(mid);
        
        //Combine
        return mergeList(l, r);
    }
private: 
    ListNode* mergeList(ListNode* l1, ListNode* l2){
        ListNode* newNode = new ListNode(0);
        ListNode* curr = newNode;
        //traversal 2 list at the same time
        while (l1 && l2) {
            if (l1->val <= l2->val) {
                curr->next = l1;
                //move
                l1 = l1->next;
            } else {
                curr->next = l2;
                //move
                l2 = l2->next;
            }
            //move
            curr = curr->next;
        }
        
        //attach remained list
        if (l1) {
            curr->next = l1; 
        }
        if (l2) {
            curr->next = l2; 
        }
        return newNode->next;
    }
};

4.Performance

Last updated