File tree Expand file tree Collapse file tree 2 files changed +25
-18
lines changed
solution/src/main/java/com/inuker/solution
test/src/main/java/com/inuker/test Expand file tree Collapse file tree 2 files changed +25
-18
lines changed Original file line number Diff line number Diff line change 9
9
public class ReverseNodesInKGroup {
10
10
11
11
public ListNode reverseKGroup (ListNode head , int k ) {
12
- int size = 0 ;
13
- ListNode dummy = new ListNode (0 ), cur = dummy , p ;
14
- for (p = head ; p != null ; p = p .next , size ++);
15
-
16
- for (p = head ; size >= k ; size -= k ) {
17
- ListNode tail = p ;
12
+ int n = 0 ;
13
+ for (ListNode node = head ; node != null ; node = node .next , n ++);
14
+ ListNode dummy = new ListNode (0 ), cur = dummy , node = head ;
15
+ for ( ; n >= k ; n -= k ) {
16
+ ListNode tail = node , next ;
18
17
for (int i = 0 ; i < k ; i ++) {
19
- ListNode next = p .next ;
20
- p .next = cur .next ;
21
- cur .next = p ;
22
- p = next ;
18
+ next = node .next ;
19
+ node .next = cur .next ;
20
+ cur .next = node ;
21
+ node = next ;
23
22
}
24
23
cur = tail ;
25
24
}
26
- cur .next = p ;
25
+ cur .next = node ;
27
26
return dummy .next ;
28
27
}
29
28
}
Original file line number Diff line number Diff line change 1
1
package com .inuker .test ;
2
2
3
3
import com .leetcode .library .ListNode ;
4
+ import com .leetcode .library .RandomListNode ;
4
5
import com .leetcode .library .TreeNode ;
5
6
6
7
import java .util .HashMap ;
@@ -24,14 +25,21 @@ public class main {
24
25
public static void main (String [] args ) {
25
26
}
26
27
27
- public boolean hasCycle (ListNode head ) {
28
- for (ListNode fast = head , slow = head ; fast != null && fast .next != null ; ) {
29
- slow = slow .next ;
30
- fast = fast .next .next ;
31
- if (fast == slow ) {
32
- return true ;
28
+ public ListNode reverseKGroup (ListNode head , int k ) {
29
+ int n = 0 ;
30
+ for (ListNode node = head ; node != null ; node = node .next , n ++);
31
+ ListNode dummy = new ListNode (0 ), cur = dummy , node = head ;
32
+ for ( ; n >= k ; n -= k ) {
33
+ ListNode tail = node , next ;
34
+ for (int i = 0 ; i < k ; i ++) {
35
+ next = node .next ;
36
+ node .next = cur .next ;
37
+ cur .next = node ;
38
+ node = next ;
33
39
}
40
+ cur = tail ;
34
41
}
35
- return false ;
42
+ cur .next = node ;
43
+ return dummy .next ;
36
44
}
37
45
}
You can’t perform that action at this time.
0 commit comments