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

LeetCode "Reverse Linked List II"

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

标签:style   blog   color   os   io   div   leetcode   log   

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"

标签:style   blog   color   os   io   div   leetcode   log   

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

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