Skip to content

Commit b178350

Browse files
refactor 142
1 parent 7e7c1f5 commit b178350

File tree

1 file changed

+21
-15
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+21
-15
lines changed

src/main/java/com/fishercoder/solutions/_142.java

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,29 +2,35 @@
22

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

5-
/**Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
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.
69
710
Note: Do not modify the linked list.
811
912
Follow up:
10-
Can you solve it without using extra space?*/
13+
Can you solve it without using extra space?
14+
*/
1115
public class _142 {
1216

17+
public static class Solution1 {
1318
public ListNode detectCycle(ListNode head) {
14-
ListNode slow = head;
15-
ListNode fast = head;
16-
while (fast != null && fast.next != null) {
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) {
1727
slow = slow.next;
18-
fast = fast.next.next;
19-
if ( slow == fast) {
20-
ListNode slow2 = head;
21-
while (slow2 != slow) {
22-
slow = slow.next;
23-
slow2 = slow2.next;
24-
}
25-
return slow;
26-
}
28+
slow2 = slow2.next;
29+
}
30+
return slow;
2731
}
28-
return null;
32+
}
33+
return null;
2934
}
35+
}
3036
}

0 commit comments

Comments
 (0)