Skip to content

Commit b2f53af

Browse files
authored
Create 0142-linked-list-cycle-ii.java
1 parent d068e08 commit b2f53af

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
public class Solution {
2+
public ListNode detectCycle(ListNode head) {
3+
ListNode slow = head;
4+
ListNode fast = head;
5+
while (fast != null && fast.next != null) {
6+
slow = slow.next;
7+
fast = fast.next.next;
8+
if (slow == fast) {
9+
break;
10+
}
11+
}
12+
13+
if (fast == null || fast.next == null) {
14+
return null;
15+
}
16+
17+
ListNode slow2 = head;
18+
while (slow != slow2) {
19+
slow = slow.next;
20+
slow2 = slow2.next;
21+
}
22+
return slow;
23+
}
24+
}

0 commit comments

Comments
 (0)