92. 反转链表 II/C++

在这里插入图片描述

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        if(!head || !head->next) return head;
        ListNode* first=new ListNode(0);
        first->next=head;
        
        int cnt=1;
        while(cnt<m){
            first=first->next;
            ++cnt;
        }
        
        ListNode* old_pre=first;
        ListNode* cur=first->next;
        ListNode* cur_next=cur->next;
        ListNode* new_pre=cur;
        ListNode* cur_next_next;
        
        while(cur && cnt<n)
        {
            cur_next_next=cur_next->next;
            cur_next->next=cur;
            cur=cur_next;
            cur_next=cur_next_next;
            ++cnt;
        }
        
        old_pre->next=cur;
        new_pre->next=cur_next;
        /*当m==1时,此时的第一个结点就变成了最后一个反转结点
          当m!=1时,就返回原先的头结点即可*/
        return m==1?cur:head;
    }
};


版权声明:本文为Zolewit原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。