首页 > 其他 > 详细

Leetcode 148. Sort List

时间:2019-03-30 21:06:15      阅读:165      评论:0      收藏:0      [点我收藏+]

148. Sort List

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
#include <iostream>
using namespace std;

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;
        //get middle node
        //not right if write: *fast = head. Otherwise, {2, 1} will not be sorted.
        ListNode *slow = head, *fast = head->next;
        while (fast && fast->next)
        {
            slow = slow->next;
            fast = fast->next->next;
        }
        ListNode *left = head, *right = slow->next;
        slow->next = NULL;
        left = sortList(left);
        right = sortList(right);
        return Merge(left, right);
    }

    ListNode *Merge(ListNode *Left, ListNode *Right) {

        if (!Left) return Right;
        if (!Right) return Left;
        ListNode *h = NULL;
        if (Left->val < Right->val) {
            h = Left;
            h->next = Merge(Left->next, Right);
        }
        else {
            h = Right;
            h->next = Merge(Left, Right->next);
        }

        return h;
    }
};

void test_data()
{
    ListNode *head = new ListNode(0);
    ListNode *p ;
    p = head;
    Solution s;
    int n = 0;
    int T = 5;
    //-1 5 3 4 0
    while (T-- && cin >> n)
    {
        ListNode *q;
        q = new ListNode(n);
        p->next = q;
        p = q;
    }

    head = head->next;
    s.sortList(head);

    while (head)
    {
        cout << head->val << " ";
        head = head->next;
    }
}

int main()
{

    test_data();

    return 0;

}

 

Leetcode 148. Sort List

原文:https://www.cnblogs.com/douzujun/p/10628871.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!