Ad Code

Responsive Advertisement

Ticker

6/recent/ticker-posts

stack operations using linked list.

   var root;

class StackNode

    {

        constructor(data)

        {

        this.data=data;

        this.next=null;

        }

    }

class Stack{

isEmpty()

    {

        if(root=null)

        {

            console.log("Stack is empty");

        }

    }

push(data)

    {

        const newNode=new StackNode(data);

        if(root==null)

        {

            root=newNode;

        }

        else

        {

            var temp=root;

            root=newNode;

            newNode.next=temp;

        }

        console.log(data+" pushed to Stack");

    }

 pop()

    {

        var popped;

        if(root==null)

        {

            console.log("Stack is empty");

        }

        else

        {

            popped=root.data;

            root=root.next;

        }

        console.log("Element popped is"+popped);

    }

 

peek()

   {

       if(root==null)

                {

                    console.log("Stack Empty");

                }

                else

                {

                    console.log("Top element of stack is:",root.data);

                   

                       

                }

   }

  

display()

    {

        let l=root;

        if(l==null)

        {

            console.log("List is empty");

        }

        else{

            while(l!=null)

                {

                    console.log(l.data);

                    l=l.next;

                }

        }

    }

}

const stck=new Stack();

stck.push(10);

stck.push(20);

stck.push(30);

stck.push(40);

stck.display();

stck.peek();

stck.pop();

stck.display();

 

Output:-

10 pushed to Stack

20 pushed to Stack

30 pushed to Stack

40 pushed to Stack

40

30

20

10

Top element of stack is: 40

Element popped is40

30

20

10

Post a Comment

0 Comments

Ad Code

Responsive Advertisement