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

LeetCode "Reorder List"

时间:2014-07-18 14:35:09      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   art   

Not very hard to figure out the solution: splitting the list into 2 halves; reverse the 2nd half and interleave the two halves.

But it takes some time to code due to a lot of details - majority of them are boudary conditions.

bubuko.com,布布扣
class Solution {
public:
    ListNode *findHalf(ListNode *p)
    {
        ListNode dummy(0); dummy.next = p;
        ListNode *sp = &dummy;
        ListNode *fp = &dummy;

        bool bOdd = false;
        ListNode *toCut = NULL;
        while(fp)
        {
            toCut = sp;
            sp = sp->next;
            fp = fp->next;
            if(fp)    fp = fp->next;
            else    bOdd = true;            
        }
        if(bOdd)
        {
            toCut->next = NULL;
            return sp;
        }
        else
        {
            ListNode *tmp = sp->next;
            sp->next = NULL;
            return tmp;
        }
    }
    ListNode * interleave(ListNode *p0, ListNode *p1)
    {
        ListNode *pa = p0;
        ListNode *pb = pa->next;
        ListNode *pc = p1;
        ListNode *pd = pc->next;
        while(pa && pc)
        {
            pa->next = pc; pc->next = pb;

            pa = pb; 
            if(pb) pb = pb->next;
            pc = pd;
            if(pd) pd = pd->next;
        }
        return p0;
    }
    ListNode *reverseList(ListNode *p)
    {
        if(!p->next) return p;

        ListNode *p0 = NULL;
        ListNode *p1 = p;        
        ListNode *p2 = p->next;        
                
        //    Reverse 
        while(p1)
        {
            p1->next = p0;
            p0 = p1;
            p1 = p2;
            if(p2) p2 = p2->next;
        }        

        return p0;
    }
    void reorderList(ListNode *head) {
        if(!head || !head->next) return;

        ListNode *p1 = findHalf(head); 
        p1 = reverseList(p1);
        interleave(head, p1);
    }
};
View Code

LeetCode "Reorder List",布布扣,bubuko.com

LeetCode "Reorder List"

标签:style   blog   http   color   os   art   

原文地址:http://www.cnblogs.com/tonix/p/3852552.html

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