Write a Java program that implement Stack ADT.

Program Code:
import java.io.*;
class StackDemo
{
public static void main(String[] args) throws Exception
{
Stack st=new Stack();
DataInputStream dis=new DataInputStream(System.in);
while(true)
{
System.out.println("MENU\n1.PUSH\n2.POP\n3.Display\n4.Exit");
System.out.println("Enter Ur Choice:");
int ch=Integer.parseInt(dis.readLine());
switch(ch)
{
case 1: System.out.println("Enter element to Push into Stack:");
int a=Integer.parseInt(dis.readLine());
st.push(a);break;
case 2: st.pop();break;
case 3:st.display();break;
case 4:System.exit(0);break;
}
}
}
}
interface StackADT
{
void push(Object o);
void pop();
void display();
}
class Stack implements StackADT
{
Object o[];
int top=-1;
int size=10;
Stack()
{
o=new Object[10];
}
Stack(int size)
{
o=new Object[size];
}
public void push(Object obj)
{
if (size==o.length-1)
System.out.println("Stack is OverFlow");
else
o[++top]=obj;
}
public void pop()
{
if(top==-1)
System.out.println("Stack is empty");
else
{
System.out.println("Element "+o[top]+"is deleted from stack");
top=top-1;
}
}
public void display()
{
if(top==-1)
System.out.println("Stack is empty");
else
System.out.println("Elements in the Stack are:");
for(int i=0;i<=top;i++)
System.out.println(o[i]);
}
}
OUTPUT:
D:\Lab>javac StackDemo.java
D:\Lab>java StackDemo
MENU
1.PUSH
2.POP
3.Display
4.Exit
Enter Ur Choice:
3
Stack is empty
MENU
1.PUSH
2.POP
3.Display
4.Exit
Enter Ur Choice:
1
Enter element to Push into Stack:
10
MENU
1.PUSH
2.POP
3.Display
4.Exit
Enter Ur Choice:
1
Enter element to Push into Stack:
20
MENU
1.PUSH
2.POP
3.Display
4.Exit
Enter Ur Choice:
2
Element 20is deleted from stack
MENU
1.PUSH
2.POP
3.Display
4.Exit
Enter Ur Choice:
2
Element 10is deleted from stack
MENU
1.PUSH
2.POP
3.Display
4.Exit
Enter Ur Choice:
2
Stack is empty
MENU
1.PUSH
2.POP
3.Display
4.Exit
Enter Ur Choice:
4
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: