-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathSolution0141.java
73 lines (65 loc) · 1.8 KB
/
Solution0141.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
62
63
64
65
66
67
68
69
70
71
72
73
// 141. 环形链表
/**
* 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) {
List<ListNode> list = new ArrayList<>();
while (head != null) {
if (list.contains(head)) {
return true;
}
list.add(head);
head = head.next;
}
return false;
}
}
/*
使用HashMap存放节点对象
*/
public class Solution {
public boolean hasCycle(ListNode head) {
HashMap<ListNode, Integer> map = new HashMap();
while (head != null) {
if (map.getOrDefault(head, 0) == 1) {
return true;
}
map.put(head, 1);
head = head.next;
}
return false;
}
}
/*
快慢指针:
1、慢指针走一步,快指针走两步
2、如果没有环,则快指针会走到空指针
3、如果有环,假设在环中,以快指针为起点,快指针距离慢指针n步,那么当慢指针走n步后的位置为2n,刚好快指针也走2n步,所以会快慢指针会相遇
*/
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
return true;
}
}
return false;
}
}