LinkedList 實現了 Deque 雙端隊列介面,提供 addFirst/addLast、removeFirst/removeLast 等 O(1) 頭尾操作,**天然適合模擬棧(LIFO)和隊列(FIFO)**,且無容量上限。
public class MyStackOrQueue<E> {
private final LinkedList<E> list = new LinkedList<>();
private final boolean isStack; // true=棧, false=隊列
public MyStackOrQueue(boolean isStack) { this.isStack = isStack; }
public void push(E e) { list.addLast(e); } // 入棧/入隊均尾插
public E pop() {
return isStack ? list.removeLast() : list.removeFirst(); // 棧取尾,隊列取頭
}
public boolean isEmpty() { return list.isEmpty(); }
}
public static void main(String[] args) {
// 測試隊列 FIFO
MyStackOrQueue<String> queue = new MyStackOrQueue<>(false);
queue.push("abc1");
queue.push("abc2");
queue.push("abc3");
while (!queue.isEmpty()) {
System.out.println("Queue: " + queue.pop()); // abc1, abc2, abc3
}
// 測試棧 LIFO
MyStackOrQueue<String> stack = new MyStackOrQueue<>(true);
stack.push("abc1");
stack.push("abc2");
stack.push("abc3");
while (!stack.isEmpty()) {
System.out.println("Stack: " + stack.pop()); // abc3, abc2, abc1
}
}


Deque<E> stack = new ArrayDeque<>(); (官方推薦,非線程安全,性能優於 Stack)。Queue<E> q = new LinkedList<>(); 或 ArrayDeque。ConcurrentLinkedQueue、ArrayBlockingQueue 等。理解 LinkedList 雙端操作特性,即可靈活構建棧/隊列。實際開發優先使用 ArrayDeque 替代舊有 Stack 和 Vector。