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

148. Sort List

时间:2016-03-09 01:21:31      阅读:138      评论: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 *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

标签:

原文地址:http://www.cnblogs.com/linjj/p/5256450.html

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