数组实现
public class Main {
public static void main(String[] args) {
ArrayStack arrayStack = new ArrayStack(3);
arrayStack.push(2);
arrayStack.push(1);
arrayStack.push(3);
arrayStack.showStack();
arrayStack.pop();
arrayStack.showStack();
}
}
class ArrayStack{
int maxSize;
int top;//栈顶
int[] array;
ArrayStack(int maxSize){
this.maxSize = maxSize;
top = -1;
array = new int[maxSize];
}
//判断栈是否满了
public boolean isFull(){
return top == maxSize-1;
}
//判断栈是否为空
public boolean isEmpty(){
return top == -1;
}
//入栈
public void push(int item){
if (isFull()){
System.out.println("栈满了 无法入栈");
return;
}
array[top + 1] = item;
top++;
}
//出栈
public int pop(){
if (isEmpty()){
throw new RuntimeException("栈是空的");
}
int value = array[top];
top--;
return value;
}
//遍历栈
public void showStack(){
if (isEmpty()){
throw new RuntimeException("栈是空的");
}
int temp = top;
for (int i = temp;i >= 0;i--){
System.out.println(array[i]);
}
}
}