Stack (Array Based)
0
import java.util.*;
class Stack
{
int arr[];
int size, top;
Stack(int s)
{
size=s;
top=-1;
arr=new int[size];
}
void push(int e)
{
if(top==size-1)
System.out.println("Stack Overflow");
else
arr[++top]=e;
}
int pop()
{
if(top==-1)
return -9999;
else
return arr[top--];
}
void show()
{
if(top==-1)
System.out.println("Empty Stack");
else
{
System.out.println("The elements in the stack:");
for(int i=top;i>=0;i--)
System.out.println(arr[i]);
}
}
public static void main()
{
Scanner in=new Scanner(System.in);
System.out.println("Enter size");
int s=in.nextInt();
int ch,e,d,c;
Stack obj=new Stack(s);
do
{
System.out.println("\f1. Push");
System.out.println("2. Pop");
System.out.println("3. Display");
System.out.println("4. Quit");
System.out.println("Enter choice");
ch=in.nextInt();
switch(ch)
{
case 1:
System.out.println("Enter a number");
e=in.nextInt();
obj.push(e);
break;
case 2:
d=obj.pop();
if(d==-9999)
System.out.println("Stack Underflow");
else
System.out.println("Deleted : "+d);
break;
case 3:
obj.show();
break;
case 4:
System.exit(0);
default: System.out.println("Wrong choice");
}
System.out.println("Enter 1 to continue...");
c=in.nextInt();
}
while(c==1);
}
}