後進先出 (LIFO)。核心操作:push (入棧)、pop (出棧)、peek (查看棧頂不移除)。
public class ToyStack {
protected int MAX_DEPTH = 10;
protected int depth = 0;
protected int[] stack = new int[MAX_DEPTH];
// 入棧
protected void push(int n) {
if (depth == MAX_DEPTH - 1) throw new RuntimeException("堆疊已滿");
stack[depth++] = n;
}
// 出棧
protected int pop() {
if (depth == 0) throw new RuntimeException("堆疊為空");
return stack[--depth]; // 先遞減再取值,實現移除效果
}
// 查看棧頂
protected int peek() {
if (depth == 0) throw new RuntimeException("堆疊為空");
return stack[depth - 1];
}
}
depth 指向下一個可寫入位置,亦代表當前元素個數pop() 使用 --depth 先移動指標再取值,邏輯上完成「移除」int 型別,進階版可用泛型支援任意物件