//数组模拟栈
@Data
public class ArrayStack {
private int maxSize; //栈的大小
private int[] stack; //模拟栈;存储数据
private int top = -1; //模拟栈顶
//初始化方法
public ArrayStack(int maxSize) {
this.maxSize = maxSize;
stack = new int[maxSize];
}
//栈满
public boolean isFull(){
return maxSize-1 == top;
}
//栈空
public boolean isNull(){
return top == -1;
}
//入栈
public void push(int value){
if(isFull()){
System.out.println("栈满了");
return;
}else{
top++;
stack[top] = value;
}
}
//出站
public int pop(){
if(isNull()){
throw new RuntimeException("暂无数据");
}else {
int i = stack[top];
top--;
return i;
}
}
//遍历
public void view(){
if(isNull()){
throw new RuntimeException("暂无数据");
}else {
for (int i = top; i >=0; i--) {
System.out.println(stack[i]);
}
}
}
}
public class Test {
public static void main(String[] args) {
ArrayStack arrayStack = new ArrayStack(3);
arrayStack.push(1);
arrayStack.push(2);
arrayStack.push(3);
arrayStack.pop();
arrayStack.pop();
arrayStack.pop();
arrayStack.pop();
arrayStack.view();
}
}