DEV Community

SREY
SREY

Posted on

Stack DataStructure in JS

// hello virtual folks !
# Lets give a shot to Stack without further ado

Stack as everybody know what it means Stack is nothing but a vector representing a list of elements that follows a particular order that is LIFO while they are deleted or removed or printed out .

Here is the code for the Stack implementation

// Stack Is nothing but a vector that follows LIFO order , it has // push , pop and peep as main Functionalities


// defining a class stack first off all 

class Stack {
    // array(vector) is used to implement the stack 

        constructor(){
            this.items = [];
        }

}
Enter fullscreen mode Exit fullscreen mode

Now lets add the code for Push and Pop operation and also Peek

  // now lets create a push function

        push(element){
            // push element 
            this.items.push(element);    
        }

Enter fullscreen mode Exit fullscreen mode

Now we will see how to add code with Pop operation !

   pop(){
            if(this.item.length == 0){
                return (" UNDERFLOW");
            }
            return this.items.pop(element);
        }
Enter fullscreen mode Exit fullscreen mode

Now here let me take a second of your's and say you why we are checking the condition

if the array is empty the pop function inside the code of stack will be having no values to delete when we solve the question by pointers we take the pointer condition as top = -1 and then we start pushing the values in it by adding pointer to 1 each time we add values to it

similarly we also need to keep an eye for removing the top element every time in the stack if the stack doesn't contains any value on the vector then it will return us the result of the if part of the code that is Underflow ! and if stack is not empty it will return us the result that we opt for that is the deleted value or element .

Now we see here how to write code for the peek

 // peek  return's the top most element but does not delete it 

        peek(){
            return this.items[this.items.length - 1]    ;
        }
Enter fullscreen mode Exit fullscreen mode

here is a small additional code for printing the stuff out one by one in Stack datastructure


  // printStack 
        printStack(){
        var str = "";
        for (var i = 0; i < this.items.length; i++)
            str += this.items[i] + " ";
        return str;
    }

Enter fullscreen mode Exit fullscreen mode

feel free to play around through the code and get your hands dirty on this !

// adding element to the stack for purpose of test 

var stack = new Stack();

stack.push(20);
stack.push(30);
stack.push(50);
stack.pop();
stack.peek();


console.log(stack.printStack());

Enter fullscreen mode Exit fullscreen mode

I hope you can get started with the implementation if you were stucked after learning the concept of Stack data Structure Hope you find it interesting , untill then G00D Bye !

Top comments (0)