-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquestion141.js
More file actions
54 lines (51 loc) · 1.26 KB
/
Copy pathquestion141.js
File metadata and controls
54 lines (51 loc) · 1.26 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
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @name Linked List Cycle
* @param {ListNode} head
* @return {boolean}
*/
// O(n)
let hasCycle = function (head) {
// 使用了额外的空间
// while (head && head.next) {
// if (!head.hasOwnProperty('rem')) {
// head.rem = 'x';
// head = head.next;
// } else {
// return true;
// }
// }
// return false;
// let map = [];
// while (head != null) {
// if (map.includes(head)) {
// return true;
// } else {
// map.push(head);
// }
// head = head.next;
// }
// return false;
if (head === null) {
return false;
}
let walker = head;
let runner = head;
// 使用两个节点遍历链表,其中一个速度为另外一个的两倍,若出现节点重复的状态
// 则说明快的那个追上了慢的那个节点,必然存在圆环
while (runner.next !== null && runner.next.next != null) {
walker = walker.next;
runner = runner.next.next;
if (walker === runner) {
return true;
}
}
return false;
};
hasCycle();