File tree Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java.util.ArrayList;
2
+ import java.util.EmptyStackException;
3
+
4
+ public class Stack<T> {
5
+ private ArrayList<T> stack = new ArrayList<>();
6
+
7
+ // Push an item onto the stack
8
+ public void push(T item) {
9
+ stack.add(item);
10
+ }
11
+
12
+ // Pop an item from the stack
13
+ public T pop() {
14
+ if (isEmpty()) {
15
+ throw new EmptyStackException();
16
+ }
17
+ return stack.remove(stack.size() - 1);
18
+ }
19
+
20
+ // Peek at the top item of the stack
21
+ public T peek() {
22
+ if (isEmpty()) {
23
+ throw new EmptyStackException();
24
+ }
25
+ return stack.get(stack.size() - 1);
26
+ }
27
+
28
+ // Check if the stack is empty
29
+ public boolean isEmpty() {
30
+ return stack.isEmpty();
31
+ }
32
+
33
+ // Get the size of the stack
34
+ public int size() {
35
+ return stack.size();
36
+ }
37
+
38
+ // Clear the stack
39
+ public void clear() {
40
+ stack.clear();
41
+ }
42
+
43
+ // Override toString for easy printing
44
+ @Override
45
+ public String toString() {
46
+ return stack.toString();
47
+ }
48
+
49
+ public static void main(String[] args) {
50
+ Stack<Integer> stack = new Stack<>();
51
+
52
+ stack.push(1);
53
+ stack.push(2);
54
+ stack.push(3);
55
+
56
+ System.out.println("Stack: " + stack);
57
+ System.out.println("Size: " + stack.size());
58
+
59
+ System.out.println("Pop: " + stack.pop());
60
+ System.out.println("Stack: " + stack);
61
+ System.out.println("Size: " + stack.size());
62
+
63
+ System.out.println("Peek: " + stack.peek());
64
+ }
65
+ }
You can’t perform that action at this time.
0 commit comments