148. Sort List

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

解题思路:归并排序的思想,空间复杂度其实是O(N)了

/**
 * 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;
        ListNode* fast = head, *slow = head, *pre = NULL;
        while(fast && fast->next) {
            pre = slow;
            slow = slow->next;
            fast = fast->next->next;
        }
        pre->next = NULL;
        ListNode* l1 = sortList(head);
        ListNode* l2 = sortList(slow);
        return merge(l1, l2);
    }
    ListNode* merge(ListNode* l1, ListNode* l2) {
        ListNode* l = new ListNode(0), *tail=l;
        while(l1 && l2) {
            if(l1->val > l2->val) {
                tail->next = l2;
                tail = l2;
                l2=l2->next;
            }
            else {
                tail->next = l1;
                tail = l1;
                l1 = l1->next;
            }
        }
        if(l1)tail->next = l1;
        else tail->next=l2;
        return l->next;
    }
};

 

posted @ 2017-10-21 22:06  Tsunami_lj  阅读(91)  评论(0编辑  收藏  举报