首页 > 其他 > 详细

LeetCode "Reverse Linked List II"

时间:2014-07-31 09:34:06      阅读:309      评论:0      收藏:0      [点我收藏+]

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;
    }
};

LeetCode "Reverse Linked List II",布布扣,bubuko.com

LeetCode "Reverse Linked List II"

原文:http://www.cnblogs.com/tonix/p/3879851.html

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