public class ArrayStackDemo {
public static void main(String[] args) throws Exception {
ArrayStack stack = new ArrayStack(5);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
System.out.println("输出栈内容");
stack.list();
System.out.println("取出栈顶后,栈中数据为:");
int pop = stack.pop();
stack.list();
}
}
//定义ArrayStack表示栈
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(){
if (top+1==maxSize)
return true;
else
return false;
}
public Boolean isEmpty(){
return top==-1;
}
//入栈方法
public void push(int parm){
if (isFull()){
System.out.println("栈已满,添加失败");
}
top+=1;
stack[top]=parm;
}
//出栈方法
public int pop() throws Exception {
if (isEmpty()){
throw new Exception("栈为空,取出失败");
}
int value = stack[top];
top--;
return value;
}
public void list(){
for (int i =0;i<top+1;i++){
System.out.println("栈中内容为:"+stack[i]);
}
}
}