/    /  Javascript-Stack

Javascript-Stack

 

The stack is a very useful data structure and has a wide range of applications. The javascript stack is a linear data structure in which the addition/removal of an element returns a particular order. The LIFO – Last in First Out and FILO – First In Last Out.

 

 stack class using array in Java script:

 

// Stack class
class Stack {

        // Array is used to implement stack
        constructor()
        {
               this.items = [];
        }

        // Functions to be implemented
        // push(item)
        // pop()
        // peek()
        // isEmpty()
        // printStack()
}

 

we have created a skeleton of a stack class that contains a constructor function in which we declare an array to implement the stack. Hence, with the creation of an object of a stack class, this constructor function would be called automatically.

 

Push:

 

Adds an element to the stack

 

// push function
push(element)
{
       // push element into the items
       this.items.push(element);
}

 

adds an element at the top of the stack.

 

Pop():

 

Removes an element from the stack, if the function is the return on an empty stack it indicates “Underflow”.

 

// pop function
pop()
{
        // return top most element in the stack
        // and removes it from the stack
       // Underflow if stack is empty
       if (this.items.length == 0)
                 return "Underflow";
       return this.items.pop();
}

 

Peek():

 

Returns the top most elements in the stack, but doesn’t delete them.

 

// peek function
peek()
{
        // return the top most element from the stack
        // but does'nt delete it.
        return this.items[this.items.length - 1];
}

 

methods:

 

isEmpty() :

 

It return true if the stack is empty.

 

// isEmpty function
isEmpty()
{
       // return true if stack is empty
       return this.items.length == 0;
}

 

printStack():

 

Returns a string in which all the elements of a stack are concatenated.

 

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