Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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.

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
posted on 2014-07-18 04:10  Tonix  阅读(146)  评论(0编辑  收藏  举报