-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path12-Stack.js
More file actions
70 lines (55 loc) · 1.32 KB
/
12-Stack.js
File metadata and controls
70 lines (55 loc) · 1.32 KB
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
/*
Stack is a LIFO data structure where insertion and deletion happen from the same end (top).
Because JS arrays already support push/pop from the end in O(1).
*/
class Stack {
constructor(){
// This array will store stack elements
this.items = [];
}
// Push element into stack
push(element){
this.items.push(element);
}
pop(){ // Remove top element from stack
if (this.isEmpty()){
return "Stack Underflow";
}
return this.items.pop();
}
peek(){ // View top element
if (this.isEmpty()){
return "Stack is empty";
}
return this.items[this.items.length - 1];
}
// Check if stack is empty
isEmpty(){
return this.items.length === 0;
}
// Size of stack
size(){
return this.items.length;
}
// Print stack (for debugging)
print(){
console.log(this.items.join(" "));
}
}
let stack = new Stack(); // creating class obj
stack.push(10);
stack.push(20);
stack.push(30);
console.log("stack:");
stack.print(); // 10 20 30
console.log("pop =>",stack.pop()); // 30
console.log("peek =>",stack.peek()); // 20
console.log("size after operation =>",stack.size()); // 2
/*
O U T P U T
stack:
10 20 30
pop => 30
peek => 20
size after operation => 2
*/