Skip to content

Commit 5242eaa

Browse files
committed
fd
1 parent 8c9adaf commit 5242eaa

File tree

2 files changed

+25
-18
lines changed

2 files changed

+25
-18
lines changed

solution/src/main/java/com/inuker/solution/ReverseNodesInKGroup.java

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -9,21 +9,20 @@
99
public class ReverseNodesInKGroup {
1010

1111
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;
1817
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;
2322
}
2423
cur = tail;
2524
}
26-
cur.next = p;
25+
cur.next = node;
2726
return dummy.next;
2827
}
2928
}

test/src/main/java/com/inuker/test/main.java

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.inuker.test;
22

33
import com.leetcode.library.ListNode;
4+
import com.leetcode.library.RandomListNode;
45
import com.leetcode.library.TreeNode;
56

67
import java.util.HashMap;
@@ -24,14 +25,21 @@ public class main {
2425
public static void main(String[] args) {
2526
}
2627

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;
3339
}
40+
cur = tail;
3441
}
35-
return false;
42+
cur.next = node;
43+
return dummy.next;
3644
}
3745
}

0 commit comments

Comments
 (0)