栈的应用场景
子程序的调用;
处理递归调用;
表达式的转换与求值;
二叉树的遍历;
图的深度优先搜索;
class ArrayStack {
int maxSize; // 栈大小
int top; // 栈顶
int[] stack; // 栈数组
// 构造函数初始化栈数组
public ArrayStack(int maxSize) {
this.maxSize = maxSize;
this.top = -1;
stack = new int[this.maxSize];
}
// 判断栈空
public boolean isEmpty() {
return top == -1;
}
// 判断栈满
public boolean isFull() {
return top == maxSize -1;
}
// 入栈
public void push(int value) {
// 栈满直接提示并退出
if (isFull()) {
System.out.println("栈满,无法继续添加数据~");
return;
}
top++;
stack[top] = value;
}
// 出栈
public int pop () {
// 栈为空直接抛出异常
if (isEmpty()) {
throw new RuntimeException("栈为空~");
}
int value = stack[top];
top--;
return value;
}
// 遍历栈
public void show() {
// 栈为空直接抛出异常
if (isEmpty()) {
throw new RuntimeException("栈为空~");
}
System.out.println();
for (int i = top; i >= 0; i--) {
System.out.printf("stack[%d]=%d\n", i, stack[i]);
}
}
}