92. 反转链表 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) {
//因为头节点有可能发生变化,使用虚拟头节点可以避免复杂的分类讨论
ListNode *dummyNode = new ListNode(-1);
dummyNode->next = head;
ListNode *pre = dummyNode;
for(int i = 0; i < left - 1; i++){
pre = pre->next;
}
ListNode *curr = pre->next;
ListNode *next;
for(int i = 0; i < right - left; i++){
/*next = curr->next;
curr->next = next->next;
pre->next = next;
next->next = curr;*/
next = curr->next;
curr->next = next->next;
next->next = pre->next;
pre->next = next;
}
return dummyNode->next;
}
};