import java.util.Scanner;
public class StackArrayDemo {
public static void main(String[] args) {
StackArray stackArray = new StackArray(4);
Scanner scanner = new Scanner(System.in);
boolean loop = true;
String key = "";
while (loop){
System.out.println("show");
System.out.println("exit");
System.out.println("push");
System.out.println("pop");
System.out.println("请输入菜单: ");
key = scanner.next();
switch (key){
case "show":
stackArray.list();
break;
case "exit":
loop = false;
break;
case "push":
System.out.println("请输入一个数: ");
int data = scanner.nextInt();
stackArray.push(data);
break;
case "pop":
int res = stackArray.pop();
System.out.println("出栈的数据是: "+res);
break;
}
}
}
}
class StackArray{
private int maxSize;
private int top = -1;
private int [] stack;
public StackArray(int maxSize) {
this.maxSize = maxSize;
stack = new int[maxSize] ;
}
public boolean isFull(){
return top == maxSize -1;
}
public boolean isEmpty(){
return top == -1;
}
public void push(int value){
if (isFull()) {
System.out.println("栈满");
return;
}
top ++;
stack[top] = value;
}
public int pop(){
if (isEmpty()){
System.out.println("栈空");
return 0;
}
int data = stack[top];
top --;
return data;
}
public void list(){
if (isEmpty()){
System.out.println("栈空");
return ;
}
for (int i = top; i >= 0 ; i --) {
System.out.printf("stack[%d] = %d\n",i,stack[i]);
}
}
}
转载请注明原文地址:https://ipadbbs.8miu.com/read-3246.html