leetcode -- Reverse Nodes in k-Group

8296 ワード

k個の要素1組のポインタ反転
 
関数呼び出しの問題!!!
 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode reverseKGroup(ListNode head, int k) {
14         // Start typing your Java solution below
15         // DO NOT write main() function
16         
17         if(head == null || k == 1)
18             return head;
19             
20         int len = 0;
21         ListNode p = head;
22         while(p != null){
23             p = p.next;
24             len ++;
25         }
26         
27         ListNode safeG = new ListNode(-1);
28         safeG.next = head;
29         ListNode pre = safeG, cur = head, post = head.next;
30         
31         int m = len / k;
32         for(int i = 0; i < m; i++){
33             post = cur.next;
34             //reverse(pre, cur, post, k);
35             int j = 0;            
36             while(post != null){
37                 ListNode tmp = post.next;
38                 post.next = cur;
39                 cur = post;
40                 post = tmp;
41                 j ++;
42                 if(j == k - 1)
43                     break;
44             }
45             ListNode tmp = pre.next;
46             pre.next = cur;
47             tmp.next = post;
48             pre = tmp;
49             cur = pre.next;
50             
51         }
52         
53         return safeG.next;
54         
55     }
56     
57     public void reverse(ListNode pre, ListNode cur, ListNode post, int k){
58         int i = 0;            
59         while(post != null){
60             ListNode tmp = post.next;
61             post.next = cur;
62             cur = post;
63             post = tmp;
64             i ++;
65             if(i == k - 1)
66                 break;
67         }
68     }
69     
70 }