示例:
输入:head = [1,2,3,4,5], left = 2, right = 4
输出:[1,4,3,2,5]
dumpyNode
指向head
,保证头结点处的插入;pre
指针指向left
处的前一个节点;cur
指针依次循环right - left
次,依次翻转节点,如下图所示。将next
指向的节点与cur
指向的节点调换顺序;class Solution {
public:
ListNode* reverseBetween(ListNode* head, int left, int right) {
ListNode *dumpyNode = new ListNode(-1, head);
ListNode *pre = dumpyNode;
for (int i = 0; i < left - 1; i++) {
pre = pre->next;
}
ListNode *cur = pre->next;
ListNode *next;
for (int i = 0; i < right - left; i++) {
next = cur->next;
cur->next = next->next; //指向next的next
next->next = pre->next; //指向pre的next
pre->next = next;
}
return dumpyNode->next;
}
};