Wednesday, 25 April 2018

Stack Implementation in JavaScript

A stack is a container of elements or objects that are inserted and removed
according to the LIFO (Last In First Out) principle. A stack is a limited acess
data structure. It involves two procedures. Push() i.e pushing an element to the stack
and Pop() popping the out the last element inserted in the stack. Many data structure
involves applications of stacks. Therefore, it is necessary to learn stack and to implement them.

Here we will use a simple JavaScript array to create an Stack.

The functions of array that will be used in the stack are:-

1. array.push() This function is used to insert the element at the last of the array.
2. array.pop() This function removes the last inserted element from the array and returns that.

Example:

//we are simply using a JavaScript array to create a stack
var stack = [];
//suppose the size of stack can't be more than 10;
var max_size = 10;
//current size will store the current size of the stack
var stack_size = 0;
function push_data(data) {
if (stack_size < max_size) {
stack.push(data);
stack_size++;
}
else {
//push function push the element at the last of the array
console.log("Stack Overflow error\n");
}
}
function pop_data() {
if (stack_size === 0) {
console.log("Stack Underflow\n");
}
else {
//pop function remove and returns the last element of the array
stack_size--;
return stack.pop();
}
}
push_data(14);
push_data(45);
var result = pop_data();
if (result !== undefined) {
console.log("The popped element is: " + result + "\n");
}
console.log("The current size of the stack is: " + stack_size + "\n");
var result = pop_data();
if (result !== undefined) {
console.log("The popped element is: " + result + "\n");
}
var result = pop_data();
if (result !== undefined) {
console.log("The popped element is: " + result + "\n");
}
console.log("The current size of the stack is: " + stack_size + "\n");


OUTPUT:



EmoticonEmoticon