package Stack;
//数组模拟栈
public class ArrayStackDemo {
public static void main(String[] args) {
ArrayStack stack=new ArrayStack(5);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
stack.list();
System.out.println("出站后");
System.out.println(stack.pop());
System.out.println(stack.pop());
stack.list();
}
}
class ArrayStack{
private int maxSize;
private int top=-1;//表示栈顶 初始化为-1
private int stack[];
public ArrayStack(int max){
maxSize = max;
stack=new int[maxSize];
}
//判断栈是否满
public boolean isFull(){
return top==maxSize-1;
}
//判断栈是否为空
public boolean isEmpty(){
return top == -1;
}
//进栈,栈中添加数据
public void push(int i){
if (isFull()){
throw new RuntimeException("栈满");
}
top++;
stack[top] = i;
}
//出栈
public int pop(){
if (isEmpty()){
throw new RuntimeException("栈空");
}
int value = stack[top];
top--;
return value;
}
//显示栈中数据 从top开始
public void list(){
if (isEmpty()){
throw new RuntimeException("栈空");
}
for(int i=top;i>-1;i--){
System.out.println("第"+(i+1)+"个数据"+stack[i]);
}
}
}