-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathDetectCycle.java
36 lines (32 loc) · 1.02 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
/*https://leetcode.com/problems/linked-list-cycle/*/
public class Solution {
public boolean hasCycle(ListNode head) {
//edge cases
if (head == null || head.next == null) return false;
if (head.next == head) return true;
//two pointer approach
ListNode singleJump = head, doubleJump = head;
singleJump = singleJump.next;
doubleJump = doubleJump.next.next;
if (singleJump == doubleJump) return true;
boolean flag = false;
while (true)
{
singleJump = singleJump.next;
//if null encountered, indicate it
if (doubleJump == null || doubleJump.next == null || doubleJump.next.next == null)
{
flag = false;
break;
}
doubleJump = doubleJump.next.next;
//if cycle detected, indicate it
if (singleJump == doubleJump)
{
flag = true;
break;
}
}
return flag;
}
}