-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path92.反转链表-ii.cpp
45 lines (42 loc) · 1.19 KB
/
92.反转链表-ii.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/*
* @lc app=leetcode.cn id=92 lang=cpp
*
* [92] 反转链表 II
*/
// @lc code=start
/**
* 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* successor = nullptr; // 后驱节点
// 反转以 head 为起点的 n 个节点,返回新的头节点
ListNode* reverseN(ListNode* head, int n) {
if (n == 1) {
// 记录第 n+1 个节点
successor = head->next;
return head;
}
// 以 head.next 为起点,反转前 n-1 个节点
ListNode* last = reverseN(head->next, n-1);
head->next->next = head;
head->next = successor;
return last;
}
ListNode* reverseBetween(ListNode* head, int left, int right) {
// base case
if (left == 1)
return reverseN(head, right);
// 前进到反转的起点触发 base case
head->next = reverseBetween(head->next, left-1, right-1);
return head;
}
};
// @lc code=end