/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode* node = new ListNode(-1);
node->next = head;
int length = 0;
while(head) {
head = head->next;
length++;
}
int n = length / k; // 翻转的子数组数
auto tail = node;
auto cur = node->next;
while(n--) { // 一共执行n次子数组遍历
int count = k - 1; // 遍历到要翻转的链表元素的前一个元素
while(cur && count--) {
auto pre = cur->next; // pre为要翻转的最后一个元素
cur->next = pre->next; // 将pre头插到tail节点后
pre->next = tail->next;
tail->next = pre;
}
tail = cur;
cur = cur->next;
}
return node->next;
}
};