-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.js
64 lines (50 loc) · 1.13 KB
/
stack.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
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class Stack {
constructor(value = "") {
this.top = null;
if (value.toString().trim()) this.top = new Node(value);
}
push(value = "") {
if (!value.toString().trim()) throw new Error("Invalid Value");
const newNode = new Node(value);
if (!this.top) return (this.top = newNode);
newNode.next = this.top;
this.top = newNode;
}
pop() {
if (!this.top) throw new Error("Stack is Empty!");
this.top = this.top.next;
}
peek() {
if (!this.top) throw new Error("Stack is Empty!");
return this.top;
}
toArray() {
const elements = [];
let currentNode = this.top;
while (currentNode) {
elements.push(currentNode.value);
currentNode = currentNode.next;
}
return elements;
}
get length() {
return this.toArray().length;
}
}
const stack = new Stack(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
stack.peek();
stack.length;
// Testing Stack
Array.from({ length: 50 }, (_, i) => i + 6).forEach((v) => stack.push(v));
stack.pop();
console.log(stack);