-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path141.LinkedListCycle.js
48 lines (35 loc) · 980 Bytes
/
141.LinkedListCycle.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
function ListNode(val, next = null) {
this.val = val;
this.next = next;
}
var hasCycle = function(head) {
if (!head || !head.next) {
return false;
}
let slow = head;
let fast = head;
while (fast && fast.next) {
slow = slow.next;
fast = fast.next.next;
if (slow === fast) {
return true;
}
}
return false;
};
const node4 = new ListNode(-4);
const node3 = new ListNode(0, node4);
const node2 = new ListNode(2, node3);
const node1 = new ListNode(3, node2);
node4.next = node2;
console.log(hasCycle(node1));
const node2_2 = new ListNode(2);
const node1_2 = new ListNode(1, node2_2);
node2_2.next = node1_2;
console.log(hasCycle(node1_2));
const node1_3 = new ListNode(1);
console.log(hasCycle(node1_3));
// Example
head = [3,2,0,-4], pos = 1
head = [1,2], pos = 0
head = [1], pos = -1