-
Notifications
You must be signed in to change notification settings - Fork 0
/
141.js
68 lines (65 loc) · 1.14 KB
/
141.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
63
64
65
66
67
68
/**
* 判断链表是否有环
* 1.打标记
* 2.快慢指针
* 3.JSON.stringify
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {boolean}
*/
var hasCycle = function (head) {
while (head) {
if (head.tag) {
return true;
}
head.tag = true;
head = head.next;
}
return false;
};
// JSON.stringify当在循环引用时会抛出异常TypeError ("cyclic object value")
var hasCycle2 = function (head) {
try {
JSON.stringify(head);
return false;
} catch (error) {
return true;
}
};
// 快慢指针
var hasCycle3 = function (head) {
if (!head) return false;
let [slow, fast] = [head, head];
while (fast && fast.next !== null) {
slow = slow.next;
fast = fast.next.next;
if (slow === fast) {
return true;
}
}
return false;
};
const linkedList = {
val: 1,
next: {
val: 2,
next: {
val: 3,
next: {
val: 4,
next: {
val: 5,
next: null,
},
},
},
},
};
const x = hasCycle(linkedList);
console.log("x", x);