-
Notifications
You must be signed in to change notification settings - Fork 0
/
linked-list-cycle.js
62 lines (53 loc) · 1.03 KB
/
linked-list-cycle.js
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
// 方法一:集合(Set)
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {boolean}
*/
var hasCycle = function (head) {
let curr = head;
let s = new Set();
while (curr) {
if (s.has(curr)) {
return true;
}
s.add(curr);
curr = curr.next;
}
return false;
};
// 方法二:快慢指针
// Reference: https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xnwzei/
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {boolean}
*/
var hasCycle = function (head) {
// 快慢指针
let fast = head,
slow = head;
while (fast && fast.next) {
// 慢指针每次走一步
slow = slow.next;
// 快指针每次走两步
fast = fast.next.next;
// 如果相遇,则说明有环
if (fast === slow) {
return true;
}
}
return false;
};