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

leet code Sort List

时间:2015-04-22 22:12:40      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

leet code Sort List

leet code Sort List

对链表使用快慢指针归并排序

Sort List

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;
        ListNode *slow = head;
        while (fast->next != NULL && fast->next->next != NULL) {
            fast = fast->next->next;
            slow = slow->next;
        } // slow 指到中间,fast 直到了结尾
        fast = slow;          // 先保留 mid 的值
        slow = slow->next;    // 相当于 mid+1
        fast->next = NULL;    // 断掉链表

        ListNode *l1 = sortList(head);
        ListNode *l2 = sortList(slow);
        return merge(l1, l2);
    }

    ListNode *merge(ListNode *l1, ListNode *l2) {  // 合并链表
        ListNode t(-1);
        ListNode *p = &t;
        while (l1 != NULL && l2 != NULL) {
            if (l1->val > l2->val) {
                p->next = l2;
                l2 = l2->next;
                p = p->next;
            } else {
                p->next = l1;
                l1 = l1->next;
                p = p->next;
            }
        }
        while (l1 != NULL) {
            p->next = l1;
            l1 = l1->next;
            p = p->next;
        }
        while (l2 != NULL) {
            p->next = l2;
            l2 = l2->next;
            p = p->next;
        }
        return t.next;         // 注意返回
    }
};

leet code Sort List

标签:

原文地址:http://www.cnblogs.com/sunznx/p/4448785.html

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