Implementation of Stack in JavaScript

Free Web development courses with real-time projects Start Now!!

Program 1

"use strict"
const ps=require("prompt-sync");
const prompt=ps({sigint:true});
let choice;
const mystack=new Array();
do
{
    console.log("----------------Stack Menu----------------------");
    console.log("1.Push");
    console.log("2.Pop");
    console.log("3.Display");
    console.log("4.Search");
    console.log("5.Sort");
    console.log("6.Reverse");
    console.log("7.Exit");
    console.log("---------------------------------------------------");
    choice=parseInt(prompt("Enter your choice"));
    switch(choice)
    {
       //push
          case 1:
         {
               let s=prompt("Enter an element for push");
               mystack.push(s);  
               break;
        }
        //pop
    case 2:
    {   
         if(mystack.length==0)
              console.log("Stack is empty");
           else
             console.log("Poped element is: "+mystack.pop());
           
    break;
    }         
    //display
    case 3:
        {
              if(mystack.length==0)
                console.log("Stack is empty");
            else
            {
                let i;
                for(i=mystack.length-1;i>=0;i--)
                console.log(mystack[i]);
            }
            break;
        }
        // Searching 
      case 4:
        {
            if(mystack.length==0)
            console.log("Stack is empty");
          else
          {
                let s=prompt("Enter an element for search");
                if(mystack.includes(s))
                   console.log("Searching success");
                else
                  console.log("Searching not success");
          }
           break;
        }  
        // Sorting 
      case 5:
       { 
        if(mystack.length==0)
        console.log("Stack is empty");
         else
          {
                mystack.sort();
                let i;
                for(i=0;i<mystack.length;i++)
                  console.log(mystack[i]);
         }
         break;
       } 
       //Reverse 
     case 6:
        {
            if(mystack.length==0)
            console.log("Stack is empty");
             else
              {
                     mystack.reverse();
                     let i;
                     for(i=mystack.length-1;i>=0;i--)
                       console.log(mystack[i]);
              }
             break;
        }  
      case 7:break;
      default:console.log("Invalid choice.....");     
    }
}while(choice!=7);

 

You give me 15 seconds I promise you best tutorials
Please share your happy experience on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *