-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlc-142.java
More file actions
31 lines (30 loc) · 761 Bytes
/
lc-142.java
File metadata and controls
31 lines (30 loc) · 761 Bytes
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
/**
* 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 || head.next == null)return null;
ListNode fast = head,slow = head;
while(fast != null && slow != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if(slow == fast) {
fast = head;
while(fast != slow) {
fast = fast.next;
slow = slow.next;
}
return fast;
}
}
return null;
}
}