码迷,mamicode.com
首页 > 其他好文 > 详细

148. Sort List

时间:2017-10-22 00:10:02      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:复杂度   排序   slow   turn   归并排序   lin   val   constant   int   

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

标签:复杂度   排序   slow   turn   归并排序   lin   val   constant   int   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!