-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.js
More file actions
38 lines (32 loc) · 677 Bytes
/
stack.js
File metadata and controls
38 lines (32 loc) · 677 Bytes
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
/*
The big O of stack methods is the following:
Insertion - O(1)
Removal - O(1)
Searching - O(n)
Access - O(n)
*/
const getStack = () => {
const getNode = (value = null, linkedNode = null) => ({ value,linkedNode });
let topNode = null;
let size = 0;
return {
push(value) {
topNode = getNode(value, topNode);
size += 1;
return true;
},
pop() {
if (!topNode) return null;
const value = topNode.value;
topNode = topNode.linkedNode;
size -= 1;
return value;
},
search(term, node = topNode) {
if (!node) return false;
if (node.value === term) return true;
return this.search(term, node.linkedNode);
},
size: () => size
}
}