/**
* 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* reverseKGroup(ListNode* head, int k) {
if (head == nullptr || k == 1) return head;
ListNode dummy(0, head);
ListNode* pre = &dummy;
ListNode* curr = head;
ListNode* next = nullptr;
// 统计链表长度
int n = 0;
while (curr) {
n++;
curr = curr->next;
}
curr = head;
while (n >= k) {
// 反转 k 个节点
next = curr->next;
for (int i = 1; i < k; ++i) {
curr->next = next->next;
next->next = pre->next;
pre->next = next;
next = curr->next;
}
pre = curr;// 将 pre 移动到当前组反转后的最后一个节点
curr = curr->next; // 将 curr 移动到下一组的第一个节点
n -= k; // 计数器减少 k,表示已经处理了 k 个节点
}
return dummy.next;
}
};
- dummy -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7
第1次循环 (i=1):
Code
next = curr->next; // next 指向 2
curr->next = next->next; // 1 -> 3 (1的next变成3)
next->next = pre->next; // 2 -> 1 (2的next变成1)
pre->next = next; // dummy -> 2 (dummy的next变成2)
next = curr->next; // next 指向 3
此时链表: dummy -> 2 -> 1 -> 3 -> 4 -> 5 -> 6 -> 7