标签:des style blog http color io os ar 使用
 View Code
View Code2. 使用一个专用的反转函数来进行反转,从头到尾遍历,遍历到K的时候,使用Pre-Next指针的方式进行反转。这个方法比递归更棒。
 1 /*
 2      * Solution 2:
 3      * 使用区间反转的办法, iteration.
 4      * */
 5     public ListNode reverseKGroup(ListNode head, int k) {
 6         if (head == null) {
 7             return null;
 8         }
 9         
10         ListNode dummy = new ListNode(0);
11         dummy.next = head;
12         
13         ListNode cur = head;
14         ListNode pre = dummy;
15         
16         int cnt = 0;
17         
18         while (cur != null) {
19             cnt++;
20             if (cnt == k) {
21                 cnt = 0;
22                 pre = reverse(pre, cur.next);
23             }
24             cur = cur.next;
25         }
26         
27         return dummy.next;
28     }
29     
30     /**
31      * Reverse a link list between pre and next exclusively
32      * an example:
33      * a linked list:
34      * 0->1->2->3->4->5->6
35      * |           |   
36      * pre        next
37      * after call pre = reverse(pre, next)
38      * 
39      * 0->3->2->1->4->5->6
40      *          |  |
41      *          pre next
42      * @param pre 
43      * @param next
44      * @return the reversed list‘s last node, which is the precedence of parameter next
45      */
46     private static ListNode reverse(ListNode pre, ListNode next){
47         ListNode cur = pre.next;
48         
49         // record the new tail.
50         ListNode last = cur;
51         while (cur != next) {
52             ListNode tmp = cur.next;
53             cur.next = pre.next;
54             pre.next = cur;
55             cur = tmp;
56         }
57         
58         last.next = next;
59         return last;
60     }
主页君的GitHub代码
ref: http://www.cnblogs.com/lichen782/p/leetcode_Reverse_Nodes_in_kGroup.html
LeetCode: Reverse Nodes in k-Group 解题报告
标签:des style blog http color io os ar 使用
原文地址:http://www.cnblogs.com/yuzhangcmu/p/4037039.html