-
Notifications
You must be signed in to change notification settings - Fork 61
/
StackPushPopExample.java
49 lines (49 loc) · 1.12 KB
/
StackPushPopExample.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import java.util.*;
public class StackPushPopExample
{
public static void main(String args[])
{
//creating an object of Stack class
Stack <Integer> stk = new Stack<>();
System.out.println("stack: " + stk);
//pushing elements into the stack
pushelmnt(stk, 20);
pushelmnt(stk, 13);
pushelmnt(stk, 89);
pushelmnt(stk, 90);
pushelmnt(stk, 11);
pushelmnt(stk, 45);
pushelmnt(stk, 18);
//popping elements from the stack
popelmnt(stk);
popelmnt(stk);
//throws exception if the stack is empty
try
{
popelmnt(stk);
}
catch (EmptyStackException e)
{
System.out.println("empty stack");
}
}
//performing push operation
static void pushelmnt(Stack stk, int x)
{
//invoking push() method
stk.push(new Integer(x));
System.out.println("push -> " + x);
//prints modified stack
System.out.println("stack: " + stk);
}
//performing pop operation
static void popelmnt(Stack stk)
{
System.out.print("pop -> ");
//invoking pop() method
Integer x = (Integer) stk.pop();
System.out.println(x);
//prints modified stack
System.out.println("stack: " + stk);
}
}