【LBLD】如何K个一组反转链表
/**
* 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* reverseN(ListNode* head, int n) {
ListNode *pre = nullptr;
ListNode *cur = head;
ListNode *nxt = head;
for (int i = n; i > 0; i--) {
nxt = cur->next;
cur->next = pre;
pre = cur;
cur = nxt;
}
return pre;
}
ListNode* reverseKGroup(ListNode* head, int k) {
if (head == nullptr) {
return head;
}
ListNode *a = head;
ListNode *b = head;
for (int i = 0; i < k; i++) {
if (b == nullptr) return head;
b = b->next;
}
head = reverseN(a, k);
a->next = reverseKGroup(b, k);
return head;
}
};