-
Notifications
You must be signed in to change notification settings - Fork 0
/
StackusingArrayList.java
54 lines (43 loc) · 1.22 KB
/
StackusingArrayList.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
50
51
52
53
54
import java.util.ArrayList;
import java.util.EmptyStackException;
class Stack {
private ArrayList<Integer> list;
Stack() {
list = new ArrayList<>();
}
boolean isEmpty() {
return list.isEmpty();
}
void push(int x) {
list.add(x);
System.out.println(x + " pushed into stack");
}
int pop() {
if (isEmpty()) {
System.out.println("Stack Underflow");
throw new EmptyStackException();
} else {
return list.remove(list.size() - 1);
}
}
int peek() {
if (isEmpty()) {
System.out.println("Stack is empty");
throw new EmptyStackException();
} else {
return list.get(list.size() - 1);
}
}
}
public class StackusingArrayList {
// Function to evaluate postfix expressions
public static void main(String args[]) {
Stack stack = new Stack();
// Basic stack operations
stack.push(10);
stack.push(20);
stack.push(30);
System.out.println(stack.pop() + " Popped from stack");
System.out.println("Top element is " + stack.peek());
}
}