首页 > 其他 > 详细

148. Sort List

时间:2017-10-21 23:54:46      阅读:589      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/tsunami-lj/p/7707113.html

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