class Stack{
constructor(){
this.array = [];
this.count = 0;
}
isEmpty(){
return this.count == 0;
}
size(){
return this.count;
}
peekTop() {
if(this.count == 0){
return "Stack is Empty";
}
return this.array[this.count-1];
}
peek(pos){
var top =this.count-1;
if(top-pos+1<0)
return "invalid index";
else
return this.array[top-pos+1];
}
push(data){
this.count++;
this.array.push(data);
}
pop(){
if(this.array.length == 0)
return "Stack is Underflow";
this.count--;
return this.array.pop();
}
print(){
if(this.count == 0){
return "Unable to Print,Stack is Empty :-(";
}
var str = "";
for (var i = this.array.length-1; i >= 0; i--)
str += this.array[i] + " ";
return str;
}
}
const arrStack = new Stack();
arrStack.push("10");
arrStack.push("20");
arrStack.push("30");
arrStack.push("40");
console.log("Peek Top element is ",arrStack.peekTop());
arrStack.push("50");
console.log("Poped element in stack ",arrStack.pop());
console.log("Peeked element at position 2",arrStack.peek(2));
console.log("element in stack
",arrStack.print());
console.log("is Stack empty? ",arrStack.isEmpty());
console.log("Size of stack is ",arrStack.size());
/**
* Time Complexity -> O(1) (all opeartion take constant time)
* Space Complexity -> O(1)
*/