/**
* 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) {
ListNode* dummyNode = new ListNode(-1);
dummyNode->next = head;
ListNode* pre = dummyNode;
for(int i = 0; i < left - 1; ++i){
pre = pre->next;
}
ListNode* cur = pre->next;
for(int i = left - 1; i < right - 1; ++i){
ListNode* next = cur->next;
cur->next = next->next;
next->next = pre->next;
pre->next = next; //pre永远是left前一个节点
}
return dummyNode->next;
}
};
LeetCode 92. 反转链表 II
最新推荐文章于 2024-07-24 14:05:37 发布