小白一枚,勿噴。下邊上代碼
棧的過程先入後出,後入先出。
public class ArryStack {
public static void main(String[] args) {
ArrayStack as = new ArrayStack(4);
String key = "";
boolean flag = true;
Scanner sc = new Scanner(System.in);
while (flag){
System.out.println("show: 顯示數據");
System.out.println("exit: 退出");
System.out.println("push: 添加");
System.out.println("pop: 取出");
System.out.println("請輸入你的選擇");
key = sc.next();
switch (key){
case "show":
as.list();
break;
case "exit":
flag = false;
case "pop":
try {
int value = as.pop();
System.out.printf("出棧的數據是%d\n", value);
}catch (Exception e){
System.out.println(e.getMessage());
}
break;
case "push":
System.out.println("請輸入你要添加的數據");
int value = Integer.parseInt(sc.next());
as.push(value);
break;
default:
break;
}
}
}
}
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 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("棧空");
return;
}
for (int i = top; i >= 0; i--){
System.out.printf("stack[%d]的數據爲%d\n", i, stack[i]);
}
}
}