思路:
代码实现:
public class ArrayStack {
private int maxSize;// 最大的尺寸
private int[] stack;// 使用数组模拟
private int top = -1;// 栈指针 , 初始为-1
public ArrayStack(int maxSize) {// 初始化
this.maxSize = maxSize;
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(top == -1){
throw new RuntimeException("栈空~~");
}
int value = stack[top];
top--;
return value;
}
// 遍历栈 == 从栈顶开始遍历
public void stackList(){
if(isEmpty()){
throw new RuntimeException("栈空~~");
}
for (int i = 0; i < maxSize ; i++) {
System.out.printf("stack[%d]=%d\n",i,stack[i]);
}
}
}
测试:
public static void main(String[] args) {
// 初始化栈
ArrayStack arrayStack = new ArrayStack(5);
// 入栈
arrayStack.push(1);
arrayStack.push(2);
arrayStack.push(5);
arrayStack.push(8);
arrayStack.push(6);
// 遍历
arrayStack.stackList();
// 出栈
int value1 = arrayStack.pop();
System.out.println(value1);
}