# 25 Reverse Nodes in K Group 每k个一组翻转链表

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example,

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

Difficulty: Hard

### 解法1

``````例如:k=3

-1(pre)->1->2->3->4(next)->5

-1->3->2->1(pre)->4(next)->5
``````
``````class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode* dummy = new ListNode(-1);
ListNode* pre = dummy,*cur = head;
int i = 0;
while(cur)
{
i++;
if (i % k == 0)
{
pre = reverseOneGroup(pre,cur->next);
cur = pre->next;
}
else
{
cur = cur->next;
}
}
ListNode* res = dummy->next;
delete dummy;
dummy = NULL;
return res;
}

//-1, 1, 2, 3, 4, 5
ListNode* reverseOneGroup(ListNode* pre,ListNode*next)
{
ListNode* last = pre->next;
ListNode* cur = last->next;
//第一次循环 1->3,2->1,-1->2,cur=3
while(cur != next)
{
last->next = cur->next;
cur->next = pre->next;
pre->next = cur;
cur = last->next;
}
return last;
}

};
``````

### 解法2

``````class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode* dummy = new ListNode(-1),*pre = dummy,*cur = pre;
int num = 0;
while (cur = cur->next) num++;
while (num >= k)
{
cur = pre->next;
for (int i = 1; i < k; i++) {
ListNode* t = cur->next;
cur->next = t->next;
t->next = pre->next;
pre->next = t;
}
pre = cur;
num -= k;
}
ListNode* res = dummy->next;
delete dummy;
dummy = NULL;
return res;
}
};
``````

### 解决3

``````class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
for (int i = 0;i < k;i++)
{
cur = cur->next;
}
}

{
ListNode* pre = tail;