92. Reverse Linked List II
在链表头添加一个虚拟源点,可以减少特判
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int left, int right) {
if(right == left) {
return head;
}
int cnt = 1;
ListNode* cur = head;
ListNode* prev = new ListNode(0, head), *next = nullptr, *vir = prev;
while(cnt < left) {
cnt++;
prev = cur;
cur = cur->next;
}
ListNode *L = prev, *L1 = cur;
while(cnt <= right) {
cnt++;
if(cnt == right) {
L->next = cur->next;
}
next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
if(cur)
L1->next = cur;
else
L1->next = nullptr;
return vir->next;
}
};
标签:prev,ListNode,cur,int,nullptr,List,next,II,92
From: https://www.cnblogs.com/smartljy/p/18449725