/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode *h = NULL, *pre = NULL;
if (!head || !head->next || k <= 1) {
return head;
}
while (head) {
int tk = k - 1;
ListNode *tail = head;
while (tk && tail) {
tail = tail->next;
--tk;
}
if (!tail) {
if (pre) {
pre->next = head;
} else {
h = pre = head;
}
head = NULL;
} else {
ListNode *next = tail->next;
ListNode *p = head->next;
head->next = NULL;
tail = head;
while (p != next) {
ListNode *temp = p->next;
p->next = head;
head = p;
p = temp;
}
if (!h) {
h = head;
} else {
pre->next = head;
}
pre = tail;
head = next;
}
}
return h;
}
};