-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackExample.java
More file actions
83 lines (51 loc) · 1.67 KB
/
StackExample.java
File metadata and controls
83 lines (51 loc) · 1.67 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import java.util.ArrayList;
import java.util.List;
public class StackExample {
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
stack.push("Apple");
stack.push("Banana");
stack.push("Cherry");
stack.push("Mango");
System.out.println("Stack: " + stack);
System.out.println("Peek: " + stack.peek());
System.out.println("Popped: " + stack.pop());
System.out.println("Popped: " + stack.pop());
System.out.println("Stack after popping: " + stack);
System.out.println("Is the stack empty? " + stack.isEmpty());
System.out.println("Size of the stack: " + stack.size());
stack.clear();
System.out.println("Stack after clearing: " + stack);
}
}
class Stack<T> {
private List<T> list = new ArrayList<>();
public void push(T element) {
list.add(element);
}
public T pop() {
if (isEmpty()) {
throw new RuntimeException("Stack is empty");
}
return list.remove(list.size() - 1);
}
public T peek() {
if (isEmpty()) {
throw new RuntimeException("Stack is empty");
}
return list.get(list.size() - 1);
}
public boolean isEmpty() {
return list.isEmpty();
}
public int size() {
return list.size();
}
public void clear() {
list.clear();
}
@Override
public String toString() {
return list.toString();
}
}