-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdetectCycle.java
53 lines (42 loc) · 1.3 KB
/
detectCycle.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
/* Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Try solving it using constant additional space.
Example :
Input :
______
| |
\/ |
1 -> 2 -> 3 -> 4
Return the node corresponding to node 3.
*/
public ListNode detectCycle(ListNode a) {
if(a==null)
return a;
ListNode slow =a, fast=a.next ;
while(slow!=fast){
if(slow == null)
return null;
slow = slow.next;
if( fast == null || fast.next==null)
return null;
else fast= fast.next.next;
}
ListNode start=slow.next;
int count=1;
while(start!=slow){
start=start.next;
count++;
}
start=a;
while(count>0)
{
start= start.next;
count--;
}
ListNode b =a;
while(b!=start)
{
b=b.next;
start=start.next;
}
return start;
}