forked from DreamCats/java-notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHasCycle.java
More file actions
61 lines (55 loc) · 1.24 KB
/
HasCycle.java
File metadata and controls
61 lines (55 loc) · 1.24 KB
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 normal;
import java.util.HashSet;
/**
* @program JavaBooks
* @description: 141.环形链表
* @author: mf
* @create: 2019/11/05 10:19
*/
/*
题目:
难度:easy
类型:链表
*/
public class HasCycle {
public static void main(String[] args) {
}
/**
* 哈希
* @param head
* @return
*/
public static boolean hasCycle(ListNode head) {
HashSet<ListNode> set = new HashSet<>();
while (head != null) {
if (set.contains(head)) {
return true;
} else {
set.add(head);
}
head = head.next;
}
return false;
}
/**
* 快慢指针
* @param head
* @return
*/
public static boolean hasCycle2(ListNode head) {
if (head != null && head.next != null) {
ListNode quick = head;
ListNode slow = head;
while (2 > 1) {
quick = quick.next;
if (quick == null) return false;
quick = quick.next;
if (quick == null) return false;
slow = slow.next;
if (slow == quick) return true;
}
} else {
return false;
}
}
}