Friday 27 January 2023

Stack program using java

package stack1;

import java.io.IOException;
import java.util.Scanner;



class Stack
{
private int tos;
private int item[];

Stack(int size)
{
        tos = -1;
       item = new int[size];
    }


void push()
{
int data;
int size=5;

if(tos==size-1)
{
System.out.println("Stack is full");
}
else
{
System.out.println("Enter the element");
Scanner sc= new Scanner(System.in);
data= sc.nextInt();
item[++tos] = data;
            //System.out.println("Pushed Item :" + item[tos]);
            //System.out.println("tos :"+tos);
}
}

void pop()
{
int data;
if(tos==-1)
{
System.out.println("Stack is empty");
}
else
{
data=item[tos];
tos=tos-1;
//System.out.println("Deleted item is"+data);
}
}

void display()
{
int i;
if(tos==-1)
{
System.out.println("Stack is empty");
}
else
{
System.out.println("Stack elements are :");
for(i=tos;i>=0;i--)
{
System.out.println(""+item[i]);
}
// System.out.println("Stack elements are :..........");
// for(i=0;i<=tos;i++)
// {
// System.out.println(""+item[i]);
// }
}
}

}



public class Stackex
{


public static void main(String[] args) throws IOException
{
boolean y=true;
        int choice;
        Stack stk = new Stack(5);
               
        do
        {
        System.out.println("1.Push");
        System.out.println("2.Pop");
        System.out.println("3.Display");
        System.out.println("4.Exit");
        System.out.println("Enter your choice");
        Scanner sc= new Scanner(System.in);
        choice= sc.nextInt();
       
       
        switch(choice)
            {
                case 1: stk.push();
                        break;
                case 2: stk.pop();
                   break;
                case 3: stk.display();
                   break;
                case 4: y = false;
                        break;
                default: System.out.println("Invalid Choice");
            }
        }
        while(y==true);
}

}

No comments:

Post a Comment