-
Notifications
You must be signed in to change notification settings - Fork 5
/
LocateCycle.java
47 lines (41 loc) · 1.15 KB
/
LocateCycle.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
/*https://leetcode.com/problems/linked-list-cycle-ii/*/
public class Solution {
public ListNode detectCycle(ListNode head) {
//edge case
if (head == null || head.next == null) return null;
//two pointer approach
ListNode slow = head, fast = head;
slow = slow.next;
fast = fast.next.next;
if (slow == fast)
return head;
boolean flag = false;
while (true)
{
slow = slow.next;
//if null encountered, indicate it
if (fast == null || fast.next == null || fast.next.next == null)
{
flag = false;
break;
}
fast = fast.next.next;
//if cycle encountered, indicate it
if (slow == fast)
{
flag = true;
break;
}
}
//if no cycle, return null
if (!flag) return null;
//standard approach to locate the cycle
slow = head;
while (slow != fast)
{
slow = slow.next;
fast = fast.next;
}
return slow;
}
}