-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path[E].[J].141.LinkedListCycle
40 lines (39 loc) · 1.07 KB
/
[E].[J].141.LinkedListCycle
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
/**
* 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) {
/* First solution using chase-and-catch */
if (head == null || head.next == null) return false;
ListNode slow = head;
ListNode fast = head.next;
while (slow != null && fast.next != null && fast.next.next != null){
if (slow == fast){
return true;
}
fast = fast.next.next;
slow = slow.next;
}
return false;
/* Second solution using hash map */
if (head == null || head.next == null) return false;
HashMap<ListNode, Boolean> hashMap = new HashMap<>();
ListNode c = head;
while (c.next != null){
if (hashMap.containsKey(c)){
return true;
}
hashMap.put(c, true);
c = c.next;
}
return false;
}
}