1. 程式人生 > >[LeetCode] Sort List

[LeetCode] Sort List

rec pre nod new XA color 劃分 put base

Sort a linked list in O(n log n) time using constant space complexity.

Example 1:

Input: 4->2->1->3
Output: 1->2->3->4

Example 2:

Input: -1->5->3->4->0
Output: -1->0->3->4->5

對鏈表進行排序

1. 要求算法復雜度為O(nlogn),只有使用快速排序,歸並排序,堆排序。

2. 選擇歸並排序。

3. 對鏈表進行遞歸劃分後合並即可。

遞歸

// Iterator
/**
 * 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* fast = head; ListNode* slow = head; ListNode* prev = NULL; while (fast && fast->next) { prev = slow; fast = fast->next->next; slow = slow->next; } prev->next = NULL; ListNode
* l1 = sortList(head); ListNode* l2 = sortList(slow); return mergeList(l1, l2); } ListNode* mergeList(ListNode* l1, ListNode* l2) { if (l1 == NULL) return l2; if (l2 == NULL) return l1; if (l1->val < l2->val) { l1->next = mergeList(l1->next, l2); return l1; } else { l2->next = mergeList(l1, l2->next); return l2; } } };

叠代

// Recursion
/**
 * 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* fast = head;
        ListNode* slow = head;
        ListNode* prev = NULL;
        while (fast && fast->next)
        {
            prev = slow;
            fast = fast->next->next;
            slow = slow->next;
        }
        prev->next = NULL;
        ListNode* l1 = sortList(head);
        ListNode* l2 = sortList(slow);
        return mergeList(l1, l2);
    }
    ListNode* mergeList(ListNode* l1, ListNode* l2)
    {
        ListNode* dummy = new ListNode(0);
        ListNode* curr = dummy;
        while (l1 && l2)
        {
            if (l1->val < l2->val)
            {
                curr->next = l1;
                l1 = l1->next;
            }
            else
            {
                curr->next = l2;
                l2 = l2->next;
            }
            curr = curr->next;
        }
        if (l1)
            curr->next = l1;
        if (l2)
            curr->next = l2;
        return dummy->next;
    }
};

[LeetCode] Sort List