Tony's Log

Algorithms, Distributed System, Machine Learning

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

Nothing special. A typical list manipulation problem.

class Solution {
public:
    ListNode *partition(ListNode *head, int x) {
        if (!head) return NULL;
        if (!head->next) return head;

        ListNode dum(-1); dum.next = head;
        ListNode *pPre = &dum;
        ListNode *plast = &dum;
        ListNode *p = head;
        while (p)
        {
            if (p->val < x)
            {
                if (pPre->next == p)
                {
                    pPre = p;
                }
                else
                {
                    ListNode *pPreNext = pPre->next;
                    //    dis-link
                    plast->next = p->next;
                    //    Move ahead                
                    pPre->next = p;
                    p->next = pPreNext;
                    pPre = p;
                    //
                    p = plast->next;
                    continue;
                }
            }
            plast = p;
            p = plast->next;
        }
        return dum.next;
    }
};
posted on 2014-08-03 06:39  Tonix  阅读(126)  评论(0编辑  收藏  举报