题解 | #链表内指定区间反转#
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类
* @param m int整型
* @param n int整型
* @return ListNode类
*/
ListNode* reverseBetween(ListNode* head, int m, int n) {
// write code here
if (!head) return nullptr;
auto dummy = new ListNode(-1), pre = dummy;
dummy->next = head;
for (int i = 0; i < m - 1; i++) pre = pre->next;
auto cur = pre->next;
// 把temp往前移动
for (int i = 0; i < n - m; i++) {
auto temp = cur->next;
cur->next = temp->next;
temp->next = pre->next;
pre->next = temp;
}
return dummy->next;
}
};
- 思路:三指针,pre->cur->temp
- 注意temp->next也需要处理
- 1、由于头节点可变,因此使用dummy空节点
- 2、移动pre指针至反转位置起点的前一个位置
- 3、固定pre节点,每次将cur->next前移至pre->next,总共进行n-m-1次
- 4、返回dummy->next
- 时间复杂度:O(n)
- 空间复杂度:O(1)
