經典教材案例:狹長通道停車場(棧)+ 門外便道(隊列),模擬車輛進出、收費、讓路全流程。本文提供基於順序棧與鏈式隊列的完整 Java 實現。
Car[] garage,top 指向棧頂,先進後出QueueNode front/rear,先進先出Car[] temp,存放為離場車輛挪動的車輛class Car {
String plate; // 車牌
int enterTime; // 進場時間
Car next; // 隊列節點指針
}
public void arrive(String plate, int time) {
if (garageTop < MAX_SIZE) { // 停車場未滿
garage[++garageTop] = new Car(plate, time);
System.out.println("車輛 " + plate + " 停入車位 " + (garageTop+1));
} else { // 停車場已滿,進入便道
enqueue(waitQueue, new Car(plate, time));
System.out.println("車輛 " + plate + " 進入便道位置 " + waitQueue.size);
}
}
public void depart(String plate, int time) {
// 1. 在棧中從頂向下搜尋
int pos = findInGarage(plate);
if (pos == -1) { System.out.println("車輛不在停車場"); return; }
// 2. 將目標車輛上方的車臨時移至 temp 棧
for (int i = garageTop; i > pos; i--) {
temp[++tempTop] = garage[i];
}
// 3. 彈出目標車輛並計費
Car target = garage[pos];
int fee = (time - target.enterTime) * RATE;
System.out.println("車輛 " + plate + " 離開,停留 " + (time-target.enterTime) + "小時,收費 " + fee);
// 4. 將 temp 棧車輛按原序移回 garage
while (tempTop >= 0) {
garage[++pos] = temp[tempTop--];
}
garageTop = pos; // 更新棧頂
// 5. 若便道有車,第一輛進入停車場
if (!waitQueue.isEmpty()) {
Car next = dequeue(waitQueue);
garage[++garageTop] = next;
next.enterTime = time; // 重新計時
System.out.println("便道車輛 " + next.plate + " 駛入車位 " + (garageTop+1));
}
}
void enqueue(Queue q, Car c) {
if (q.rear == null) q.front = q.rear = c;
else { q.rear.next = c; q.rear = c; }
q.size++;
}
Car dequeue(Queue q) {
Car c = q.front;
q.front = q.front.next;
if (q.front == null) q.rear = null;
q.size--;
c.next = null;
return c;
}
輸入序列(n=2):
A 1 5 A 2 10 D 1 15 A 3 20 A 4 25 A 5 30 D 2 35 D 4 40 E 0 0
關鍵輸出片段:
車輛 1 停入車位 1 車輛 2 停入車位 2 車輛 3 進入便道位置 1 車輛 4 進入便道位置 2 車輛 1 離開,停留 10小時,收費 30 便道車輛 3 駛入車位 2 車輛 2 離開,停留 25小時,收費 75 ...
ArrayDeque 替代手寫棧/隊列,生產級代碼更健壯;