Thursday, 11 August 2016

Stack operation in java

import java.io.*;
class stack
{
final int max=3;
int a[]=new int[max];
int top=-1;
void push(int x)
{
if(top>=max-1)
System.out.println("Stack over flow");
else
{
top++;
a[top]=x;
}
}
void pop()
{
if(top<0)
System.out.println("Stack under flow");
else
{
System.out.println("deleted item is.."+a[top]);
top--;
}
}
void display()
{
if(top<0)
System.out.println("no elemnets in the stack to display");
else
{
System.out.println("The elements in the stack are..\n");
for(int i=top;i>=0;i--)
{
System.out.println(a[i]);
}
}
}
}
class stackop
{
public static void main(String args[])throws IOException
{
int ch;int x;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
stack st=new stack();
while(true)
{
System.out.println("\n1. Push");
System.out.println("2. POP");
System.out.println("3. Display");
System.out.println("4. Exit");
System.out.println("Enter your choice");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1: System.out.println("Enter the element to be inserted");
    x=Integer.parseInt(br.readLine());
    st.push(x);
    break;
case 2:    st.pop();
    break;
case 3: st.display();
    break;
case 4:System.exit(0);
}
}
}
}
Post a Comment