1 递归反转链表
代码语言:javascript复制class Solution {
public:
// 在[first, end)区间内反转链表
ListNode* reverseBetween(ListNode* first, ListNode* end) {
ListNode* pre = nullptr;
ListNode* cur = first;
while (cur != end) {
auto next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
ListNode* reverseKGroup(ListNode* head, int k) {
if (!head) return nullptr;
auto first = head;
auto end = head;
for (int i = 0; i < k; i ) {
if (!end) return head;
end = end->next;
}
auto newHead = reverseBetween(first, end);
// 之前的first到现在就是end - 1
first->next = reverseKGroup(end, k);
return newHead;
}
};