-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinked_list_cycle_ii.java
53 lines (46 loc) · 1.17 KB
/
Linked_list_cycle_ii.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.netease.kaola.act.compose;
public class Linked_list_cycle_ii {
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
ListNode(int x, ListNode next) {
this.val = x;
this.next = next;
}
}
public ListNode detectCycle(ListNode head) {
if (head == null || head.next == null) {
return null;
}
if (head.next == head) {
return head;
}
ListNode slow = head;
ListNode fast = head;
while (slow != null && fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
break;
}
}
if (slow == null || fast == null) {
return null;
}
if (slow == head) {
return head;
}
for (slow = head; slow != null && fast != null; ) {
slow = slow.next;
fast = fast.next;
if (slow == fast) {
return slow;
}
}
return null;
}
}