Skip to content

Commit c74f021

Browse files
authored
Add file Linked_list_cycle_ii.java
1 parent 48c742b commit c74f021

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

Linked_list_cycle_ii.java

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package com.netease.kaola.act.compose;
2+
3+
public class Linked_list_cycle_ii {
4+
5+
public static class ListNode {
6+
int val;
7+
ListNode next;
8+
9+
ListNode(int x) {
10+
val = x;
11+
next = null;
12+
}
13+
14+
ListNode(int x, ListNode next) {
15+
this.val = x;
16+
this.next = next;
17+
}
18+
}
19+
20+
public ListNode detectCycle(ListNode head) {
21+
if (head == null || head.next == null) {
22+
return null;
23+
}
24+
if (head.next == head) {
25+
return head;
26+
}
27+
ListNode slow = head;
28+
ListNode fast = head;
29+
while (slow != null && fast != null && fast.next != null) {
30+
slow = slow.next;
31+
fast = fast.next.next;
32+
if (slow == fast) {
33+
break;
34+
}
35+
}
36+
if (slow == null || fast == null) {
37+
return null;
38+
}
39+
if (slow == head) {
40+
return head;
41+
}
42+
for (slow = head; slow != null && fast != null; ) {
43+
slow = slow.next;
44+
fast = fast.next;
45+
if (slow == fast) {
46+
return slow;
47+
}
48+
}
49+
return null;
50+
}
51+
}
52+
53+

0 commit comments

Comments
 (0)