-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path142.java
34 lines (34 loc) · 794 Bytes
/
142.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
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head==null) return null;
ListNode fast = head;
ListNode slow = head;
boolean isCycle = false;
while(fast.next!=null&&fast.next.next!=null){
fast = fast.next.next;
slow = slow.next;
if(fast==slow){
isCycle =true;
break;
}
}
if(!isCycle) return null;
fast = head;
while(fast!=slow){
fast = fast.next;
slow = slow.next;
}
return slow;
}
}