Tony's Log

Algorithms, Distributed System, Machine Learning

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

Just corner case..

class Solution {
public:
    ListNode *reverseBetween(ListNode *head, int m, int n) {
        if(m == n) return head;

        ListNode *pPre = NULL;
        ListNode *p1 = head;
        ListNode *p2 = head->next;
        ListNode *pPost = NULL;    if(p2) pPost = p2->next;
        
        //    Find m first
        int om = m;
        while(--om)
        {
            if(!pPre) pPre = head;        
            else pPre = pPre->next;
            p1 = p2;
            if(p2) p2 = p2->next;
            if(pPost) pPost = pPost -> next;
        }
        
        ListNode *pPreM = pPre;
        ListNode *pM = p1;

        //    Reverse it
        int cnt = n - m;
        while(cnt --)
        {
            p1->next = pPre;
            
            p2->next = p1;

            pPre = p1;
            p1 = p2;
            p2 = pPost;
            if(pPost) pPost = pPost->next;
        }
        
        if(pPreM)    pPreM->next = p1;
        else head = p1;
        if(pM) pM->next = p2;

        return head;
    }
};
posted on 2014-07-31 08:06  Tonix  阅读(122)  评论(0编辑  收藏  举报