首页 > 其他 > 详细

LeetCode----Sort List

时间:2014-02-17 06:19:24      阅读:285      评论:0      收藏:0      [点我收藏+]

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 *fast(head), *slow(head), *list2(NULL);
        fast = fast->next;
        while(fast && fast->next)
        {
            fast = fast->next->next;
            slow = slow->next;
        }
        list2 = slow->next;
        slow->next = NULL;
        head = sortList(head);
        list2 = sortList(list2);
        return mergeList(head, list2);
    }
private:
    ListNode *mergeList(ListNode *lhs, ListNode *rhs)
    {
        ListNode *list(NULL), *rear(NULL);
        while(lhs && rhs)
        {
            if(lhs->val <= rhs->val){
                if(rear){
                  rear->next = lhs;
                  rear = rear->next;
                }
                else{
                  list = rear = lhs;
                }
                lhs = lhs->next;
            }
            else
            {
                if(rear){
                    rear->next = rhs;
                    rear = rear->next;
                }
                else{
                    list = rear = rhs;
                }
                rhs = rhs->next;
            }
        }
        if(lhs){
            if(rear) rear->next = lhs;
            else list = lhs;
        }
        if(rhs){
            if(rear) rear->next = rhs;
            else list = rhs;
        }
        return list;
    }
};


LeetCode----Sort List

原文:http://blog.csdn.net/shoulinjun/article/details/19290237

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