/**
* 数组实现栈
*/
public class ArrayStack {
private int top;
private int capacity;
private int[] array;
public ArrayStack() {
this.top = -1;
this.capacity = 1;
this.array = new int[capacity];
}
public boolean isEmpty(){ // 判断栈是否为空
//if the condition is true then 1 is returned else 0 is returned
return (top == -1);
}
public boolean isStackFull(){ //判断栈是否为满
return (top == array.length);
}
public void push(int data){ //入栈操作
if (isStackFull()){ // 判断栈是否已满, 栈满了则抛出栈满异常
System.out.println("Stack Overflow");
}else {
array[++top] = data; //入栈
}
}
public int pop(){ // 删除栈顶元素
if (isEmpty()) {
System.out.println("Stack is Empty"); //栈为空则抛出空栈异常
return 0;
}else {
return array[--top]; //出栈
}
}
public void deleteStack(){ //删除栈
top = -1;
}
}
局限性:栈的最大空间必须预先声明且不能改变。试图对一个满栈执行入栈操作将产生一个针对简单数组这种特定实现栈方式的异常。