package 数据结构.栈;
/**
* Created with IntelliJ IDEA.
*
* @Author: 你的名字
* @Date: 2021/09/05/8:38
* @Description:
*/
public class ArrayStackDemo {
public static void main(String[] args) {
ArrayStack arrayStack = new ArrayStack(10);
arrayStack.push(1);
arrayStack.showStack();
}
}
class ArrayStack{
private int maxSize;
private int[] stack;
private int top=-1;
public ArrayStack(int maxSize){
this.maxSize=maxSize;
stack=new int[this.maxSize];
}
public boolean ifFull(){
return top==maxSize-1;
}
public boolean ifEmpty(){
return top==-1;
}
//入栈
public void push(int value){
if(ifFull()){
System.out.println("栈满");
}
top++;
stack[top]=value;
}
//出栈
public int pop(){
if(ifEmpty()){
throw new RuntimeException("栈空");
}
int value=stack[top];
top--;
return value;
}
//打印栈
public void showStack(){
if(ifEmpty()){
System.out.println("栈空");
return;
}
for (int i =top ; i >=0 ; i--) {
System.out.printf("stack[%d]=%d \n",i,stack[i]);
}
}
}
数组实现栈的操作
最新推荐文章于 2024-11-09 23:45:15 发布