148. Sort List

Posted 向日葵的祈愿

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了148. Sort List相关的知识,希望对你有一定的参考价值。

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

链表的归并排序。

/**
 * 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 *tail = head, *mid = head, *pre = head;
        
        while (tail && tail->next) {
            pre = mid;
            mid = mid->next;
            tail = tail->next->next;
        }
        //change pre next to null, make two sub list(head to pre, p1 to p2)
        pre->next = NULL;
        
        ListNode *h1 = sortList(head);
        ListNode *h2 = sortList(mid);
        
        return merge(h1, h2);
    }
    ListNode* merge(ListNode *h1, ListNode *h2) {
        if (h1 == NULL) return h2;
        if (h2 == NULL) return h1;
        
        if (h1->val < h2->val) {
            h1->next = merge(h1->next, h2);
            return h1;
        } else {
            h2->next = merge(h1, h2->next);
            return h2;
        }
    }
};

 

以上是关于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