-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathLinkedListCycle.java
61 lines (59 loc) · 1.46 KB
/
LinkedListCycle.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
52
53
54
55
56
57
58
59
60
61
package io.ziheng.list.leetcode;
import java.util.HashSet;
import java.util.Set;
/**
* LeetCode 141. Linked List Cycle
* https://leetcode.com/problems/linked-list-cycle/
*/
public class LinkedListCycle {
public boolean hasCycle(ListNode head) {
if (head == null) {
return false;
}
// return hasCycleHashing(head);
return hasCycleTwoPointer(head);
}
/**
* Linked List has Cycle -> Two Pointer
*
* Time Complexity: O(n)
* Space Complexity: O(1)
*
* @param head
* @return boolean
*/
private boolean hasCycleTwoPointer(ListNode head) {
ListNode pFast = head;
ListNode pSlow = head;
while (pFast != null && pFast.next != null) {
pFast = pFast.next.next;
pSlow = pSlow.next;
if (pFast == pSlow) {
return true;
}
}
return false;
}
/**
* Linked List has Cycle -> Hashing
*
* Time Complexity: O(n)
* Space Complexity: O(n)
*
* @param head
* @return boolean
*/
private boolean hasCycleHashing(ListNode head) {
Set<ListNode> aSet = new HashSet<>();
ListNode currentNode = head;
while (currentNode != null) {
if (aSet.contains(currentNode)) {
return true;
}
aSet.add(currentNode);
currentNode = currentNode.next;
}
return false;
}
}
/* EOF */