leetcode第一刷_Reverse Linked List II

翻转链表绝对是终点项目。应该掌握的,这道题要求的是翻转一个区间内的节点。做法事实上非常相似,仅仅只是要注意判定開始是头的特殊情况,这样head要更新的。还有就是要把翻转之后的尾部下一个节点保存好,要么链表就断掉了。

一趟就能够,遇到节点直接翻转,最后把整个翻转的链表再翻转一次,就实现了。

class Solution {
public:
    ListNode *reverseBetween(ListNode *head, int m, int n) {
        if(head == NULL || m==n)    return head;
        ListNode *l1, *l2, *pNode = head, *pre = NULL, *nt, *ntt, *nttt;
        int i = 1;
        while(pNode){
            if(i<m) {pre = pNode; i++; pNode = pNode->next;}
            else{
                l1 = pNode;
                nt = l1;
                ntt = l1->next;
                l1->next = NULL;
                while(ntt&&i<n){
                    nttt = ntt->next;
                    ntt->next = nt;
                    nt = ntt;
                    ntt = nttt;
                    i++;
                }
                l2 = ntt;
                l1->next = l2;
                if(pre){
                    pre->next = nt;
                    return head;
                }else{
                    return nt;
                }
            }
        }
    }
};


原文地址:https://www.cnblogs.com/wgwyanfs/p/7060790.html