簡易模擬棧(Stack):
- 後進先出
- 從棧頂插入資料
- 從棧頂取出資料
public class Test {
public static void main(String[] args) {
ArrayStack stack = new ArrayStack(4);
System.out.println("輸入show,顯示棧中所有值");
System.out.println("輸入push,將值加入棧頂");
System.out.println("輸入pop,從棧頂取出值");
System.out.println("輸入exit,退出程式");
System.out.println("請輸入一個指令~~");
Scanner scanner = new Scanner(System.in);
boolean shouldStop = false;
while(scanner.hasNext()) {
switch (scanner.next()) {
case "show":
stack.loopStack();
break;
case "push":
System.out.println("請輸入要入棧的值:");
stack.push(scanner.nextInt());
break;
case "pop":
try {
int popVal = stack.pop();
System.out.printf("出棧的值:%d\n", popVal);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case "exit":
scanner.close();
shouldStop = true;
break;
}
if(shouldStop) break;
}
}
}
// imitate stack by array
class ArrayStack {
private int stackSize;
private int[] stack;
private int top;
public ArrayStack(int stackSize) {
this.stackSize = stackSize;
this.stack = new int[stackSize];
this.top = -1;
}
/**
* check stack is empty?
* @return
*/
public boolean isEmpty() {
return top == -1;
}
/**
* check stack is full?
* @return
*/
public boolean isFull() {
return top == stackSize - 1;
}
/**
* push value to the top of stack
* @param value
*/
public void push(int value) {
if (isFull()) {
System.out.println("棧滿~~");
return;
}
top++;
stack[top] = value;
}
/**
* get out the top of stack value
* @return
*/
public int pop() {
if (isEmpty()) {
throw new RuntimeException("棧空,沒有資料");
}
int value = stack[top];
top--;
return value;
}
/**
* loop stack from the top
*/
public void loopStack() {
if (isEmpty()) {
System.out.println("棧空,沒有資料");
return;
}
for (int i = top; i >= 0; i--) {
System.out.printf("stack[%d]=%d\n", i, stack[i]);
}
}
}
如有敘述錯誤,還請不吝嗇留言指教,thanks!