We have already seen about Array Data Structure. Stack data structure is implemented using arrays. With push(), pop(), shift(), unshift() we create stack . For creation of stack we always prefer push() and pop(). Now let us implement stack data structure.
Methods to implement Stack Data Structure :
- push() – adds an element at top of the stack
- pop() – removes the top most element of the stack and if it is called on an empty stack returns ‘underflow’
- peek() – similar to pop() returns top most element but does not delete it.
- isEmpty() – return true if stack is empty.
- printStack() – returns a string in which all elements of the stack are concatenated.
Program to implement Stack :
class Stack {
constructor() {
this.items = [];
}
// add element to the stack
add(element) {
return this.items.push(element);
}
// remove element from the stack
remove() {
if(this.items.length > 0) {
return this.items.pop();
}
}
// view the last element
peek() {
return this.items[this.items.length - 1];
}
// check if the stack is empty
isEmpty(){
return this.items.length == 0;
}
// the size of the stack
size(){
return this.items.length;
}
// empty the stack
clear(){
this.items = [];
}
}
let stack = new Stack();
stack.add(10);
stack.add(20);
stack.add(30);
stack.add(40);
console.log(stack.items);
stack.remove();
console.log(stack.items);
console.log(stack.peek());
console.log(stack.isEmpty());
console.log(stack.size());
stack.clear();
console.log(stack.items);