-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstructy-104-linkedListCycle.js
88 lines (66 loc) · 1.56 KB
/
structy-104-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
77
78
79
80
81
82
83
84
85
86
87
88
// https://structy.net/problems/premium/linked-list-cycle
class Node {
constructor(val) {
this = val;
this.next = null;
}
}
// p: head of ll
// r: boolean
// // two poninters time O(n) space O(1)
const linkedListCycle = (head) => {
let p1 = head;
let p2 = head;
let firstInteraction = true
while (p2 && p2.next) {
if (p1 === p2 && !firstInteraction) return true;
p1 = p1.next;
p2 = p2.next.next;
firstInteraction = false
}
return false;
};
// // // two poninters time O(n) space(1)
// const linkedListCycle = (head) => {
// let p1 = head;
// let p2 = head.next;
// while (p2 && p2.next) {
// if (p1 === p2) return true;
// p1 = p1.next;
// p2 = p2.next.next;
// }
// return false;
// };
// // time O(n) space O(n)
// const linkedListCycle = (head) => {
// const visited = new Set();
// let cur = head;
// while (cur) {
// if (visited.has(cur)) return true;
// visited.add(cur);
// cur = cur.next;
// }
// return false;
// };
// const a = new Node("a");
// const b = new Node("b");
// const c = new Node("c");
// const d = new Node("d");
// a.next = b;
// b.next = c;
// c.next = d;
// d.next = b; // cycle
// // _______
// // / \
// // a -> b -> c -> d
// true
const a = new Node("a");
const b = new Node("b");
const c = new Node("c");
const d = new Node("d");
a.next = b;
b.next = c;
c.next = d;
// a -> b -> c -> d
// false
console.log(linkedListCycle(a));