Reverse Nodes in k-Group

 1 public class Solution {
 2     public ListNode reverseKGroup(ListNode head, int k) {
 3         // Start typing your Java solution below
 4         // DO NOT write main() function
 5         
 6         if(head == null || k == 1)
 7             return head;
 8             
 9         int len = 0;
10         ListNode p = head;
11         while(p != null){
12             p = p.next;
13             len ++;
14         }
15         
16         ListNode safeG = new ListNode(-1);
17         safeG.next = head;
18         ListNode pre = safeG, cur = head, post = head.next;
19         
20         int m = len / k;
21         for(int i = 0; i < m; i++){
22             post = cur.next;
23             //reverse(pre, cur, post, k);
24             int j = 0;            
25             while(post != null){
26                 ListNode tmp = post.next;
27                 post.next = cur;
28                 cur = post;
29                 post = tmp;
30                 j ++;
31                 if(j == k - 1)
32                     break;
33             }
34             ListNode tmp = pre.next;
35             pre.next = cur;
36             tmp.next = post;
37             pre = tmp;
38             cur = pre.next;
39             
40         }
41         
42         return safeG.next;
43         
44     }
45     
46     public void reverse(ListNode pre, ListNode cur, ListNode post, int k){
47         int i = 0;            
48         while(post != null){
49             ListNode tmp = post.next;
50             post.next = cur;
51             cur = post;
52             post = tmp;
53             i ++;
54             if(i == k - 1)
55                 break;
56         }
57     }
58 }
原文地址:https://www.cnblogs.com/jasonC/p/3431755.html