Skip to content

Commit 106a6ea

Browse files
refactor 142
1 parent 0d06265 commit 106a6ea

File tree

1 file changed

+17
-27
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+17
-27
lines changed

Diff for: src/main/java/com/fishercoder/solutions/_142.java

+17-27
Original file line numberDiff line numberDiff line change
@@ -2,35 +2,25 @@
22

33
import com.fishercoder.common.classes.ListNode;
44

5-
/**
6-
* 142. Linked List Cycle II
7-
8-
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
9-
10-
Note: Do not modify the linked list.
11-
12-
Follow up:
13-
Can you solve it without using extra space?
14-
*/
155
public class _142 {
166

17-
public static class Solution1 {
18-
public ListNode detectCycle(ListNode head) {
19-
ListNode slow = head;
20-
ListNode fast = head;
21-
while (fast != null && fast.next != null) {
22-
slow = slow.next;
23-
fast = fast.next.next;
24-
if (slow == fast) {
25-
ListNode slow2 = head;
26-
while (slow2 != slow) {
27-
slow = slow.next;
28-
slow2 = slow2.next;
29-
}
30-
return slow;
7+
public static class Solution1 {
8+
public ListNode detectCycle(ListNode head) {
9+
ListNode slow = head;
10+
ListNode fast = head;
11+
while (fast != null && fast.next != null) {
12+
slow = slow.next;
13+
fast = fast.next.next;
14+
if (slow == fast) {
15+
ListNode slow2 = head;
16+
while (slow2 != slow) {
17+
slow = slow.next;
18+
slow2 = slow2.next;
19+
}
20+
return slow;
21+
}
22+
}
23+
return null;
3124
}
32-
}
33-
return null;
3425
}
35-
}
3626
}

0 commit comments

Comments
 (0)