-
-
Notifications
You must be signed in to change notification settings - Fork 421
/
linked-list-cycle.java
45 lines (35 loc) · 1.16 KB
/
linked-list-cycle.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
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null){
return false;
}
ListNode slowPtr = head;
ListNode fastPtr = head;
/** Approach
// 1. if no cycle exists AND
// a. if there are even number of nodes then fast pointer will be pointing to null.
// b. else there are odd number of nodes then fast pointer will be pointing to last node.
// 2. if slow pointer meet fast pointer that interprets there exists a loop
*/
while (fastPtr != null && fastPtr.next != null) {
// move slow pointer one node at a time
slowPtr = slowPtr.next;
// move fast pointer two nodes at a time
fastPtr = fastPtr.next.next;
if (slowPtr == fastPtr)
return true;
}
return false;
}
}