Thursday, 14 December 2017

Stack in Java with the help of Interface

Design an interface named Stack with the following methods:

(a) push and pop elements from the stack.

(b) check whether the stack is empty or not.

Implement the stack with the help of arrays and if the size of the array becomes too small to hold Java the elements, create a new one. Test this interface by inheriting it in its subclass Stacktest.java.

Program:




import java.util.Scanner;
interface Stack{
void push(int s[]);
int pop(int s[]);
void display(int s[]);
}

class stack1 implements Stack{
    Scanner sc=new Scanner(System.in);
    int top=-1;
public void push(int s[]){
int val;
if(top>=s.length-1)
{
       System.out.println("Stack is overflow");
         return;
    }
System.out.println(" Enter Any Value:");
val=sc.nextInt();
top++;
        s[top]=val;
}

public int pop(int s[])
{
       if(top==-1)
       {
        System.out.println(" Stack is Underflow");  
               return(-1);
        }
        return(s[top--]);
  }
  public void display(int s[])
  {
int i;
        if(top==-1)
        {
        System.out.println(" Stack is Empty");
        }
        else
        {
        System.out.println(" Stack is------");
for(i=top;i>=0;i--)
{
                System.out.println(s[i]);
}
        }
     }
}

class StackTest{
public static void main(String ag[]){
      Scanner sc=new Scanner(System.in);
      int s[]=new int[5];
      stack1 s1=new stack1();
      int y,choice;
do
       {
System.out.println();
System.out.println("----MENU----");
System.out.println(" 1. PUSH");
System.out.println(" 2. POP");
System.out.println(" 3. DISPLAY");
System.out.println(" 4. QUIT");
System.out.println("Enter Your Choice:");
choice=sc.nextInt();
switch(choice)
{
case 1:
s1.push(s);
break;

case 2:
y=s1.pop(s);
if(y!=-1)
{
System.out.println("The popeed value is "+y);
                 }
break;

case 3:
s1.display(s);
break;

case 4:
System.out.println(" GOOD BYE");
break;

default:
                System.out.println(" Invalid Choice");              
           }
}while(choice!=4);
    }
}

OUTPUT:


No comments:

Post a Comment