# LeetCode（15）： 每k个一组翻转链表

hard！

• 你的算法只能使用常数的额外空间。
• 你不能只是单纯的改变节点内部的值，而是需要实际的进行节点交换。

```-1->1->2->3->4->5
|           |
pre         next

-1->3->2->1->4->5
|  |
pre next```

C++解法一：

``` 1 /**
2  * Definition for singly-linked list.
3  * struct ListNode {
4  *     int val;
5  *     ListNode *next;
6  *     ListNode(int x) : val(x), next(NULL) {}
7  * };
8  */
9 class Solution {
10 public:
11     ListNode *reverseKGroup(ListNode *head, int k) {
13         ListNode *dummy = new ListNode(-1);
14         ListNode *pre = dummy, *cur = head;
16         int i = 0;
17         while (cur) {
18             ++i;
19             if (i % k == 0) {
20                 pre = reverseOneGroup(pre, cur->next);
21                 cur = pre->next;
22             } else {
23                 cur = cur->next;
24             }
25         }
26         return dummy->next;
27     }
28     ListNode *reverseOneGroup(ListNode *pre, ListNode *next) {
29         ListNode *last = pre->next;
30         ListNode *cur = last->next;
31         while(cur != next) {
32             last->next = cur->next;
33             cur->next = pre->next;
34             pre->next = cur;
35             cur = last->next;
36         }
37         return last;
38     }
39 };```

C++解法二：

``` 1 class Solution {
2 public:
3     ListNode* reverseKGroup(ListNode* head, int k) {
4         ListNode *dummy = new ListNode(-1), *pre = dummy, *cur = pre;
6         int num = 0;
7         while (cur = cur->next) ++num;
8         while (num >= k) {
9             cur = pre->next;
10             for (int i = 1; i < k; ++i) {
11                 ListNode *t = cur->next;
12                 cur->next = t->next;
13                 t->next = pre->next;
14                 pre->next = t;
15             }
16             pre = cur;
17             num -= k;
18         }
19         return dummy->next;
20     }
21 };```

C++解法三：

``` 1 class Solution {
2 public:
3     ListNode* reverseKGroup(ListNode* head, int k) {
5         for (int i = 0; i < k; ++i) {
7             cur = cur->next;
8         }
12     }
13     ListNode* reverse(ListNode* head, ListNode* tail) {
14         ListNode *pre = tail;
15         while (head != tail) {