# LeetCode 笔记系列六 Reverse Nodes in k-Group [学习如何逆转一个单链表]

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,
Given this linked list: 1->2->3->4->5

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

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

 1 public static ListNode reverseKGroup(ListNode head, int k) {
2         // Start typing your Java solution below
3         // DO NOT write main() function
5         int idx = 0;
6         ListNode pp = null;
9             if(k <= 1 || c == null)return firstGHead;
10             for(int i = 0; i < k - 1&& c != null;i++) {
11                 c = c.next;
12             }
13             if(c == null) break;
15             int i = k - 1;
17             ListNode pn = p.next;
18             ListNode lastEnd = pp;
19             while(i > 0){
22                 pn = p.next;
23                 pp = lastEnd;
24                 int swap = 0;
25                 while(swap < i){
26                     p.next = pn.next;
27                     pn.next = p;
28                     if(pp != null)
29                         pp.next = pn;
30                     pp = pn;
31                     pn= p.next;
32                     swap++;
33                 }
34                 i--;
35             }
38             pp = c;
39         }
40         return firstGHead;
View Code

 1 ListNode dummy = new ListNode(0);
3         ListNode pre = dummy;
6         while(cur != null){
7             last.next = cur.next;
8             cur.next = pre.next;
9             pre.next = cur;
10             cur = last.next;
11         }
12         head = dummy.next;

/**
* Reverse a link list between pre and next exclusively
* an example:
* 0->1->2->3->4->5->6
* |           |
* pre        next
* after call pre = reverse(pre, next)
*
* 0->3->2->1->4->5->6
*          |  |
*          pre next
* @param pre
* @param next
* @return the reversed list's last node, which is the precedence of parameter next
*/
private static ListNode reverse(ListNode pre, ListNode next){
ListNode last = pre.next;//where first will be doomed "last"
ListNode cur = last.next;
while(cur != next){
last.next = cur.next;
cur.next = pre.next;
pre.next = cur;
cur = last.next;
}
return last;
}
reverse range

 1 public static ListNode reverseKGroup2(ListNode head, int k) {
3         ListNode dummy = new ListNode(0);
5         ListNode pre = dummy;
6         int i = 0;
8             i++;
9             if(i % k ==0){
17     }