-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStack-Operation.java
More file actions
51 lines (45 loc) · 1.18 KB
/
Stack-Operation.java
File metadata and controls
51 lines (45 loc) · 1.18 KB
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
class Stack {
private java.util.ArrayList<Integer> stack;
public Stack() {
stack = new java.util.ArrayList<>();
}
public void push(int item) {
stack.add(item);
System.out.println("Pushed " + item + " onto the stack.");
}
public Integer pop() {
if (!isEmpty()) {
int item = stack.remove(stack.size() - 1);
System.out.println("Popped " + item + " from the stack.");
return item;
} else {
System.out.println("Stack is empty. Cannot pop.");
return null;
}
}
public boolean isEmpty() {
return stack.isEmpty();
}
public Integer peek() {
if (!isEmpty()) {
int item = stack.get(stack.size() - 1);
System.out.println("Top item is " + item);
return item;
} else {
System.out.println("Stack is empty.");
return null;
}
}
public static void main(String[] args) {
Stack s = new Stack();
s.push(10);
s.push(20);
s.push(30);
s.peek();
s.pop();
s.peek();
s.pop();
s.pop();
s.pop();
}
}