思路:定义maxSize固定栈的大小,top指向栈顶,初始化为-1,bottom指向栈底初始化为0。当top == -1时,栈为空。当top == maxSize-1时,栈满。
public class ArrayStack {
int maxSize;
int top;
int bottom;
Object[] arr;
public ArrayStack(int maxSize){
this.maxSize = maxSize;
arr = new Object[maxSize];
top = -1;
}
/**
* 栈是否空
*/
public boolean isEmpty(){
return top == -1;
}
/**
* 栈是否满
*/
public boolean isFull(){
return top == maxSize-1;
}
/**
* 出栈
*/
public Object pop(){
if(isEmpty()){
throw new RuntimeException("栈是空的");
}else{
return arr[top--];
}
}
/**
* 入栈
*/
public Object push(){
if(isFull()){
throw new RuntimeException("栈已满");
}else{
return arr[++top];
}
}
}