Stack Data Structure Using Javascript

Nikhil Bobade - Apr 30 '21 - - Dev Community

Stack:-

A Stack is a commonly used linear data structure a stack data structure follows particular operations that are performed Stack is behaved like Last in first out (LIFO) In this, we have three basic operations.

  1. Push Method
  2. Pop Method
  3. Peek Method
  4. Is Empty Method

Push Method :

The push method is adding data into any type of data into the stack.

Peek Method:

Peek is a very easy operation this method is given you which item or data is on the top of the list so this peek method returns the top element

Pop Method:

Pop is removed the top item from the stack

Is Empty Method:

The is empty method is very important this return if the stack is empty then its return true.

Alt Text

When we use push D is added then call stack on top is D then we use pop then D is removed from the stack.

Stack example using Javascript
//© Inspiration from coding garden


class Stack {
    constructor(){
        this.data = {};
        this.size = 0;
    }

    push(item){
        this.data[this.size] = item;
        this.size +=1
    }

    peek(){
       return this.data[this.size - 1];
    }

    pop(){
        const item = this.peek();
        this.size -= 1;
        delete this.data[this.size];
        return item;
    }
}

const launguage = new Stack();

launguage.push("Typescript")
launguage.push("Angular");
launguage.push("JS");
launguage.push("C++");

console.log(launguage)
console.log(launguage.pop())
console.log(launguage)
console.log(launguage.pop())
console.log(launguage)

Enter fullscreen mode Exit fullscreen mode

Output

Alt Text

I hope you like this also comments about your thoughts.

For more content follow me on Instagram @developer_nikhil27.

If you want to more support me then buy me a coffee.

Thank you.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player