Implement Stack in java
Program
import java.util.Stack;
import java.util.Scanner;//Scanner class reads data from input stream
class Stackdemo
{
public static void main(String[] args)
{
int size=5;
Stack<Integer> obj=new Stack<Integer>();//Stack class is accepting wrapper class Integer type of data
Scanner s=new Scanner(System.in);
while(true)
{
System.out.println("1.Push");
System.out.println("2.Pop");
System.out.println("3.Display");
System.out.println("4.Quit");
System.out.println("Enter choice");
int choice=s.nextInt();
switch(choice)
{
case 1:System.out.println("Enter the element to be pushed into stack");
int e=s.nextInt();
if(obj.size()==size)
System.out.println("Stack overflow");
else
obj.push(e);//pushes element into stack
break;
case 2:if(obj.isEmpty())//checks whether stack is empty or not
System.out.println("Stack underflow");
else
System.out.println("Element popped from stack"+obj.pop());
break;
case 3:if(obj.isEmpty())
System.out.println("Stack is empty");
else
{
System.out.println("Stack elements");
for(int i=obj.size()-1;i>=0;--i)//obj.size() gives no of elements in stack
System.out.println(obj.get(i));//get()-returns the element from stack based on position
}
break;
case 4:System.exit(0);
default:System.out.println("Wrong choice");
}
}
}
}
Expected Output
1.Push
2.Pop
3.Display
4.Quit
Enter choice
1
Enter the element to be pushed into stack
10
1.Push
2.Pop
3.Display
4.Quit
Enter choice
1
Enter the element to be pushed into stack
20
1.Push
2.Pop
3.Display
4.Quit
Enter choice
1
Enter the element to be pushed into stack
30
1.Push
2.Pop
3.Display
4.Quit
Enter choice
1
Enter the element to be pushed into stack
40
1.Push
2.Pop
3.Display
4.Quit
Enter choice
1
Enter the element to be pushed into stack
50
1.Push
2.Pop
3.Display
4.Quit
Enter choice
1
Enter the element to be pushed into stack
60
Stack overflow
1.Push
2.Pop
3.Display
4.Quit
Enter choice
3
Stack elements
50
40
30
20
10
1.Push
2.Pop
3.Display
4.Quit
Enter choice
2
Element popped from stack50
1.Push
2.Pop
3.Display
4.Quit
Enter choice
2
Element popped from stack40
1.Push
2.Pop
3.Display
4.Quit
Enter choice
3
Stack elements
30
20
10
1.Push
2.Pop
3.Display
4.Quit
Enter choice
2
Element popped from stack30
1.Push
2.Pop
3.Display
4.Quit
Enter choice
2
Element popped from stack20
1.Push
2.Pop
3.Display
4.Quit
Enter choice
2
Element popped from stack10
1.Push
2.Pop
3.Display
4.Quit
Enter choice
3
Stack is empty
1.Push
2.Pop
3.Display
4.Quit
Enter choice
2
Stack underflow
1.Push
2.Pop
3.Display
4.Quit
Enter choice
4
Comments