数组模拟栈
//表示栈
class ArrayStack{
private int maxSize;//栈的大小
private int[] stack; //数组模拟栈,数据放在该数组
private int top = -1; //top表示栈顶,初始化-1,表示没有数据
public ArrayStack(int maxSize) {
this.maxSize = maxSize;
stack = new int[maxSize];//初始化数组
}
//栈满
public boolean isFull(){
return top == maxSize-1;
}
//栈空
public boolean isEmpty(){
return top==-1;
}
//入栈push
public void push(int value){
if (isFull()){
System.out.println("栈满了");
return;
}
top++;
stack[top] = value;
}
//出栈pop
public int pop(){
if (isEmpty()){
throw new RuntimeException("栈空了");
}
int value = stack[top];
top--;
return value;
}
//遍历栈,遍历时需要从栈顶开始显示数据
public void list(){
if (isEmpty()){
System.out.println("栈空,没有数据");
}
for (int i = top; i >= 0 ; i--) {
System.out.printf("stack[%d]=%d \n",i,stack[i]);
}
}
}
测试
public static void main(String[] args) {
ArrayStack arrayStack = new ArrayStack(4);
String key = "";
boolean loop = true;
Scanner sc = new Scanner(System.in);
while (loop){
System.out.println("s(show):显示栈");
System.out.println("e(exit):退出栈");
System.out.println("p(push):添加栈");
System.out.println("g(pop):拿出栈");
key = sc.next();
switch (key){
case "s":
arrayStack.list();
break;
case "e":
sc.close();
loop=false;
break;
case "p":
System.out.println("请输入一个数字");
int value = sc.nextInt();
arrayStack.push(value);
break;
case "g":
try {
int res = arrayStack.pop();
System.out.println("取出的数据为"+res);
}catch (Exception e){
System.out.println(e.getMessage());
}
break;
}
}
}