-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.js
More file actions
43 lines (36 loc) · 854 Bytes
/
stack.js
File metadata and controls
43 lines (36 loc) · 854 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
39
40
41
42
43
class Stack {
constructor() {
this.stack = [];
}
push(item) {
this.stack.push(item);
}
pop() {
if (this.isEmpty()) {
return "empty stack";
}
return this.stack.pop();
}
peek() {
if (this.isEmpty()) {
return "empty stack";
}
return this.stack[this.stack.length - 1];
}
isEmpty() {
return this.stack.length === 0;
}
size() {
return this.stack.length;
}
}
// Example
const stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
console.log(`Stack after pushing: ${stack.stack}`);
console.log(`Let's take a peek on the top: ${stack.peek()}`);
console.log(`Popped item: ${stack.pop()}`);
console.log(`Stack after popping: ${stack.stack}`);
console.log(`Is stack empty? ${stack.isEmpty()}`);