package zhan;
//数组实现栈
public class ArrayStack {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
class Stack{
//栈长,栈顶
private int maxSize=5;
private int top=-1;
private int[] arr= new int[maxSize];
//判断栈空
public boolean isEmpty() {
return top == -1;
}
//判断栈满
public boolean isFull() {
return top == maxSize - 1;
}
//入栈
public void push(int value) {
//判满
if(isFull()) {
System.out.println("栈满,无法添加数据");
return;
}
top++;
arr[top]= value;
}
//出栈
public int pop() {
//判空
if(isEmpty()) {
throw new RuntimeException("栈空,没有数据");
}
int value = arr[top];
top--;
return value;
}
//展示栈
public void list() {
//判空
if(isEmpty()) {
throw new RuntimeException("栈空,没有数据");
}
for(int i=top;i>=0;i--) {
System.out.printf("arr[%d]=%d\n",i,arr[i]);
}
}
}
数组实现简单的栈
最新推荐文章于 2023-04-02 20:06:11 发布