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

Leetcode:Sort List 对单链表归并排序

时间:2014-07-02 08:47:34      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:单链表   leetcode   merge   归并排序   

Sort a linked list in O(n log n) time using constant space complexity.

看到O(n log n)的排序算法,适合单链表的首先想到的就是归并排序

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode * findListMid(ListNode * head)
    {
        if(head == NULL)return NULL;
        ListNode * fast = head;
        ListNode * slow = head;
        while(fast->next)
        {
            if(fast->next->next)
            {
                fast = fast->next->next;
                slow = slow->next;
            }
            else
                return slow;
        }
        return slow;
    }
    ListNode * merge(ListNode * list1,ListNode * list2)
    {
        if(list1 == NULL)return list2;
        if(list2 == NULL)return list1;
        ListNode * head = NULL;
        if(list1->val >= list2->val)
        {
            head = list2;
            list2 = list2->next;
        }
        else
            if(list1->val < list2->val)
            {
                head = list1;
                list1 = list1->next;
            }
            ListNode * tail = head;
        while(list1 && list2)
        {
            if(list1->val >= list2->val)
            {
                tail->next = list2;
                tail = list2;
                list2 = list2->next;
            }  
            else
                if(list1->val < list2->val)
                {
                    tail->next = list1;
                    tail = list1;
                    list1 = list1->next;
                }  
        }
        if(list1)
            tail->next = list1;
        if(list2)
            tail->next = list2;
        return head;
    }
    ListNode *sortList(ListNode *head) {
        if(head == NULL)return NULL;
        if(head->next == NULL)return head;
        ListNode * mid = findListMid(head);
        ListNode * m = mid->next;
        mid->next = NULL;
        ListNode * list1 = sortList(head);
        ListNode * list2 = sortList(m);
        ListNode * list = merge(list1,list2);
        return list;
    }
};


Leetcode:Sort List 对单链表归并排序,布布扣,bubuko.com

Leetcode:Sort List 对单链表归并排序

标签:单链表   leetcode   merge   归并排序   

原文地址:http://blog.csdn.net/u012118523/article/details/36221205

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