Skip to content

Commit 44f70fd

Browse files
authored
Merge pull request #3457 from Tetsuya3850/patch-7
Create 0142-linked-list-cycle-ii.java
2 parents 725d65c + b2f53af commit 44f70fd

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)