LeetCode "Reverse Linked List II"

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;
    }
};
原文地址:https://www.cnblogs.com/tonix/p/3879851.html