首页 > 其他 > 详细

leetcode-Sort List

时间:2016-05-24 13:36:30      阅读:148      评论:0      收藏:0      [点我收藏+]

题目链接:

https://leetcode.com/problems/reorder-list/

分析:

注意这里寻找中间节点的时候需要增加一个哑巴节点,否则1->2这种就会出错,具体代码如下:

class Solution {
public:
    ListNode* sortList(ListNode* head) {
        if(head == NULL || head->next == NULL)
        {
            return head;
        }
        ListNode dummy(-1);
        dummy.next = head;
        ListNode *slow = &dummy;
        ListNode *fast = &dummy;
        while(fast != NULL && fast->next != NULL)
        {
            slow = slow->next;
            fast = fast->next->next;
        }

        ListNode *p1 = head;
        ListNode *p2 = slow->next;
        slow->next = NULL;
        ListNode *pp1 = sortList(p1);
        ListNode *pp2 = sortList(p2);
        return mergeList(pp1, pp2);
    }
private:
    ListNode *mergeList(ListNode *p1, ListNode *p2)
    {
        if(p1 == NULL && p2 == NULL)
        {
            return NULL;
        }
        else if(p1 == NULL)
        {
            return p2;
        }
        else if(p2 == NULL)
        {
            return p1;
        }
        else
        {
            ListNode dummy(-1);
            ListNode *cur = &dummy;
            while(p1 != NULL && p2 != NULL)
            {
                if(p1->val < p2->val)
                {
                    cur->next = p1;
                    p1 = p1->next;
                }
                else
                {
                    cur->next = p2;
                    p2 = p2->next;
                }
                cur = cur->next;
            }
            if(p1 != NULL)
            {
                cur->next = p1;
            }
            if(p2 != NULL)
            {
                cur->next = p2;
            }
            return dummy.next;
        }
    }
};

 

leetcode-Sort List

原文:http://www.cnblogs.com/shirley-ict/p/5523041.html

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