Repository navigation
Expand file tree
/
Copy pathStackModel.java
More file actions
84 lines (68 loc) · 1.98 KB
/
Copy pathStackModel.java
File metadata and controls
84 lines (68 loc) · 1.98 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
84
package com.simulator;
import java.util.ArrayList;
import java.util.EmptyStackException;
import java.util.List;
public class StackModel {
private List<Integer> stack;
private int maxSize;
public StackModel() {
this(20); // Default max size
}
public StackModel(int maxSize) {
this.maxSize = maxSize;
this.stack = new ArrayList<>();
}
public void push(int value) {
if (stack.size() >= maxSize) {
throw new IllegalStateException("Stack overflow: Maximum capacity reached");
}
stack.add(value);
System.out.println("Pushed: " + value + " | Stack size: " + stack.size());
}
public int pop() {
if (isEmpty()) {
throw new EmptyStackException();
}
int value = stack.remove(stack.size() - 1);
System.out.println("Popped: " + value + " | Stack size: " + stack.size());
return value;
}
public int peek() {
if (isEmpty()) {
throw new EmptyStackException();
}
return stack.get(stack.size() - 1);
}
public boolean isEmpty() {
return stack.isEmpty();
}
public int size() {
return stack.size();
}
public void clear() {
stack.clear();
System.out.println("Stack cleared");
}
public boolean isFull() {
return stack.size() >= maxSize;
}
public List<Integer> getElements() {
return new ArrayList<>(stack);
}
public int getCapacity() {
return maxSize;
}
@Override
public String toString() {
if (isEmpty()) {
return "Stack: []";
}
StringBuilder sb = new StringBuilder("Stack (top to bottom): [");
for (int i = stack.size() - 1; i >= 0; i--) {
sb.append(stack.get(i));
if (i > 0) sb.append(", ");
}
sb.append("]");
return sb.toString();
}
}