The two important parts of a stack data structure
are the pop and push functions. Before you pop
, you need to check whether the stack is empty. If itβs not empty you can remove and return the last element (the element that was added to the stack last). Remember to decrement the pointer (top
) before you leave the function.
Similarly, before we conduct a push
operation, we need to check whether the stack is full. If not we can insert the element at the end of the stack. Remember to increment the pointer (top) before exiting the function.
Finally, you can use the main
function to call push
and pop
functions to examine the behavior of the stack we just created. Of course, you can improve this stack by including functions like peek
, getSize
, etc.
xxxxxxxxxx
class Stack {
// Array is used to implement stack
constructor() {
this.items = [];
}
β
// Functions we'll need
push(val) {
// Push element into the items array
this.items.push(val);
}
pop() {
// Return top most element in the stack
// and remove it from the stack
if (!this.items.length) return "Underflow";
return this.items.pop();
}
peek() {
// return the top most element from the stack
// but does'nt delete it.
return this.items[this.items.length - 1];
}
getSize() {
return this.items.length;
}
// print()
}