LeetCode92 反转链表Ⅱ
idea:参考上一道全部反转,所以反转链表部分代码实现,我觉得重点在于集中不同情况的分类讨论。一共四类情况需要考虑,有前有后,有前无后,有后无前,无前无后。

class Solution {
public:
ListNode *reverseBetween(ListNode *head, int left, int right) {
// 设置 dummyNode 是这一类问题的一般做法
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;
ListNode *next;
for (int i = 0; i < right - left; i++) {
next = cur->next;
cur->next = next->next;
next->next = pre->next;
pre->next = next;
}
return dummyNode->next;
}
};
-
时间复杂度:O(N)O(N),其中 NN 是链表总节点数。最多只遍历了链表一次,就完成了反转。
-
空间复杂度:O(1)O(1)。只使用到常数个变量。
浙公网安备 33010602011771号