148. Sort List

Posted 为了更优秀的你,加油!

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
    }
};

 

以上是关于148. Sort List的主要内容,如果未能解决你的问题,请参考以下文章

148. Sort List

[LeetCode] 148. Sort List

148. Sort List

[Lintcode]98. Sort List/[Leetcode]148. Sort List

148. Sort List

148. Sort List