Search Here

Java program to implement Stack operations


/* Stack Operations */

import java.io.*;

class MyStack
{
 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
 private int stack[],size,top;
 
 public MyStack()
 {
  top=-1;
  System.out.print("Enter size of the stack: ");
  try
  {
   size=Integer.parseInt(br.readLine());
   stack=new int[size];
  }
  catch(Exception e)
  {
   System.err.println(e);
  }
 }
 
 public void push()
 {
  if(top==size-1)
   System.out.println("Stack overflow");
  else
  {
   System.out.println("Enter data to be pushed: ");
   try
   {
    stack[++top]=Integer.parseInt(br.readLine());
   }
   catch(Exception e)
   {
    System.err.println(e);
   }
  }
 }
 
 public void pop()
 {
  if(top==-1)
   System.out.println("Stack underflow");
  else
   System.out.println("Popped item is: "+stack[top--]);
 }
 
 public void display()
 {
  if(top==-1)
   System.out.println("Stack is empty");
  else
  {
   System.out.println("Elements of the stack are: ");
   for(int i=top;i>-1;i--)
    System.out.println(stack[i]);
  } 
 }
}

class Main
{
 public static void main(String args[])
 {
  BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  MyStack obj=new MyStack();
  
  try
  {
   int exit=0;
   while(exit==0)
   {
    System.out.println("1.PUSH\t2.POP\t3.DISPLAY\t4.EXIT");
    System.out.print("\tEnter your choice: ");
    int ch=Integer.parseInt(br.readLine());
    
    switch(ch)
    {
        case 1:obj.push();
               break;
        case 2:obj.pop();
               break;
        case 3:obj.display();
               break;
        case 4:exit=1;
            break;
        default:System.out.println("Wrong choice given");
    }
   }
  }
  catch(Exception e)
  {
   System.err.println(e);
  }
 }
}



JAVA program to implement Stack operations
Output

No comments:

Post a Comment