LeetCode 25 Reverse Nodes in k-Group

小细节太多了,需要注意!!!

 1 public ListNode reverseKGroup(ListNode head, int k) {
 2     if (head == null || head.next == null) {
 3         return head;
 4     }
 5     ListNode dummy = new ListNode(0);
 6     dummy.next = head;
 7     ListNode cur = dummy;
 8     
 9     while (cur != null) {
10         cur = reverseK(cur, k);
11     }
12     return dummy.next;
13 }
14 
15 // 1  ->  2  ->  3  ->  4  ->  5 ->  6  k = 2
16 //head         node
17 //             cur    next
18 // 2 -> 1   ->  3  ->  4  
19 private ListNode reverseK(ListNode head, int k) {
20 ListNode tail = head;
21 ListNode prev = head;
22 ListNode n1 = head.next; //翻转list中的第一个元素。
23 for (int i = 0; i < k; i++) {
24 tail = tail.next;
25 //这里要判断剩余部分不够k的数的时候。直接返回null,不进行任何操作。
26 if (tail == null) {
27 return null;
28 }
29 }
30 
31 ListNode next = tail.next;
32     //           1 ->  2  ->  3     |    ->  4  ->  5
33     //   head  first        tail            next 
34 
35 ListNode newHead = reverse(head.next, tail);
36     //    head      3 -> 2  ->  1 ->   |   4  ->  5  -> null
37     //            newH        first       next
38 
39 prev.next = newHead;
40 n1.next = next;
41 //不要返回next。 把n1当作下一次调用的dummy node, 所以每次返回的都是dummy node
42 return n1;
43 }
44 
45 private ListNode reverse(ListNode head, ListNode tail) {
46     if (head == tail) {
47         return head;
48     }
49     ListNode prev = null, cur = head;
50     while (cur != tail) {
51         ListNode next = cur.next;
52         cur.next = prev;
53         prev = cur;
54         cur = next;
55     }
56     
57     if (cur == null) {
58         return prev;
59     }
60     cur.next = prev;
61     return cur;
62 }
原文地址:https://www.cnblogs.com/mayinmiao/p/8492103.html