-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.js
71 lines (67 loc) · 1.68 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
65
66
67
68
69
70
71
//refer this program for better understanding of stack.
class Stack {
constructor(capacity) {
this.top = -1;
this.arr = [];
this.capacity = capacity;
}
push(item) {
if (this.top === this.capacity-1) {
console.log("Stack Overflow.");
}
this.top++;
this.arr[this.top] = item;
console.log(item, "Got pushed in stack.");
this.print();
}
pop() {
if (this.top === -1) {
console.log("Stack Underflow");
}
let result = this.arr[this.top];
this.top--;
console.log(result, "Got popped in stack.");
this.arr.pop();
this.print();
}
peek() {
if(this.top===-1){
console.log("stack is empty, so there is no items at top of stack.");
this.print();
}
console.log("Top of the stack is", this.top);
this.print();
}
isEmpty(){
if(this.top===-1){
console.log("Stack is empty now.");
this.print()
}
else{
console.log(`Stack is not empty, there are ${this.arr.length} elements in stack.`);
this.print();
}
}
isFull(){
if(this.top===this.capacity){
console.log("Stack is Full.");
this.print();
}else{
console.log(`Stack is not full. there are ${this.capacity-this.top-1} items space available in stack.`);
this.print();
}
}
print(){
console.log("Stack is :",...this.arr)
}
}
let s1= new Stack(5);
s1.push(2);
s1.push(5);
s1.push(9);
s1.push(5);
s1.push(9);
s1.pop();
s1.peek();
s1.isEmpty();
s1.isFull();