-
Notifications
You must be signed in to change notification settings - Fork 20
/
LinkedListCycle.js
76 lines (67 loc) · 1.41 KB
/
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
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
74
75
76
/**
* Given a linked list, determine if it has a cycle in it.
*
* Follow up:
* Can you solve it without using extra space?
*/
function ListNode(val) {
this.val = val;
this.next = null;
}
/**
* @param {ListNode} head
* @return {boolean}
*/
// Time limit exceeded.
/*let hasCycle = function (head) {
if (head == null || head.next == null) {
return false;
}
let node = head.next;
while (node !== head) {
if (node == null) {
return false;
}
node = node.next;
}
return true;
};*/
// Accepted.
let hasCycle = function (head) {
let slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow === fast) {
return true;
}
}
return false;
};
if (hasCycle(null) === false) {
console.log("pass")
} else {
console.error("failed")
}
if (hasCycle(new ListNode(0)) === false) {
console.log("pass")
} else {
console.error("failed")
}
let node0 = new ListNode(0);
node0.next = new ListNode(1);
node0.next.next = node0;
if (hasCycle(node0)) {
console.log("pass")
} else {
console.error("failed")
}
let node1 = new ListNode(0);
node1.next = new ListNode(1);
node1.next.next = new ListNode(2);
node1.next.next.next = new ListNode(0);
if (hasCycle(node1) === false) {
console.log("pass")
} else {
console.error("failed")
}