Stack using Interface in Java

import java.util.*;

interface Stk
{
  void push(int g);
  int pop();
  boolean isempty();
  boolean isfull();
  int peek();
  void disp();
};

class MyStack implements Stk
{
  int ar[];
  int top;
  MyStack(int p)
   {
    ar=new int[p];
    top=-1;
   }

  public void push(int g)
   {
    ar[++top]=g;
   }

  public int pop()
   {
    int t;
    t=ar[top--];
    return t;
   }

  public int peek()
   {
    int t;
    t=ar[top];
    return t;
   }

  public boolean isfull()
   {
    if(top==ar.length)
     return true;
    else
     return false;
   }

  public boolean isempty()
   {
    if(top==-1)
     return true;
    else
     return false;
   }

  public void disp()
   {
    int t;
    t=top;
    while(t>=0)
     {
      System.out.println(ar[t]);
      t--;
     }
}
}

class StackPrg
 {
  public static void main(String []ar)
   {
    Scanner sc=new Scanner(System.in);
    int t,ch,v;
    System.out.println("Enter the size of the array : ");
    t=sc.nextInt();
    MyStack ob=new MyStack(t);
    while(true)
     {
      System.out.println("1)Push \n 2)Pop \n 3)Peek \n 4)Display \n 5)Exit");
      System.out.println("Enter your choice");
      ch=sc.nextInt();

    switch(ch)
     {
      case 1: System.out.println("Enter the value : ");
v=sc.nextInt();
if(!ob.isfull())
 ob.push(v);
else
 System.out.println("No More Space");
break;
      case 2: if(!ob.isempty())
 {
  v=ob.pop();
  System.out.println("The popped Value is"+v);
 }
else
 System.out.println("Nothing to display");
break;
      case 3:
if(!ob.isempty())
 {
  v=ob.peek();
  System.out.println("The top most Value is"+v);
 }
else
 System.out.println("Nothing to display");
break;
      case 4:
if(!ob.isempty())
 {
  System.out.println("Values in the stack are");
  ob.disp();  
 }
else
 System.out.println("Nothing to display");
break;
      case 5:
System.exit(0);
      default:
System.out.println("Wrong choice");
     }
}
}
}

Comments

Popular posts from this blog

JAVA program to add two distance

Print Pattern using C