LeetCode 92. 反转链表 II
原题链接
中等
作者:
回归线
,
2021-03-27 21:29:45
,
所有人可见
,
阅读 195
/**
* 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 (left == right || !head->next) {
return head;
}
auto dummy = new ListNode(-1);
dummy->next = head;
auto a = dummy;
for (int i = 0; i< left -1; ++i) {
a = a->next;
}
auto b = a->next;
auto c = b->next;
auto d = c->next;
for (int i = 0; i< right- left; ++i) {
d = c->next;
c->next = b;
b = c;
c = d;
}
a->next->next = c;
a->next = b;
return dummy->next;
}
};