| 位置 | 方法 | 異常行為 | 備註 |
| 尾部(隊列入隊) | add()、addLast()、offer()、offerLast() | add 系拋異常(理論不會),offer 系返回 boolean | offer 為 Queue 接口規範 |
| 首部(棧壓入/雙端隊列) | addFirst()、offerFirst()、push() | 同理 | push() 為棧語義,內部調用 addFirst() |
逆序遍歷:descendingIterator()
Iterator<String> it = list.descendingIterator();
while (it.hasNext()) {
System.out.print(it.next() + ",");
}
// 輸出:3333,2222,1111,head,
無需手動反轉,高效支持從尾到頭遍歷。
特定元素移除:首次 vs 末次出現
removeFirstOccurrence("3333"); // 移除首個匹配,返回 boolean
removeLastOccurrence("2222"); // 移除最後匹配,返回 boolean
內部委託 remove(Object) 實現,按方向查找首個匹配節點斷鏈。
實戰場景選型建議
- 棧(LIFO):
push(E) / pop() / peek(),語義清晰
- 隊列(FIFO):
offer(E) / poll() / peek(),符合 Queue 規範
- 雙端隊列:
offerFirst/pollFirst、offerLast/pollLast 成對使用
- 高併發環境:改用
ConcurrentLinkedDeque 或 ArrayBlockingQueue
- 隨機訪問頻繁:優先選
ArrayList
完整運行示例輸出
[1111, 2222, 3333]
[head, 1111, 2222, 3333]
3333,2222,1111,head,
head
head
head
head
3333
3333
[head, 1111, 2222, 3333, tail]
[----, head, 1111, 2222, 3333, tail]
[----, head, 1111, 2222, 3333, tail, ====]
----
head
====
[xyz, 1111, 2222, 3333, tail]
xyz
[1111, 2222, 3333, tail]
1111
[2222, 3333, tail]
true
[2222, tail]
tail
[2222]
true
[]
掌握 LinkedList 全套首尾操作語義,能讓你在棧、隊列、雙端隊列等經典數據結構場景下游刃有餘,寫出更具表達力的代碼。
- 上一篇文章: Java 進階教程:Stack 棧結構原理與實戰應用
- 下一篇文章: Java 進階教程:Vector 同步列表特性與現代替代方案
Copyright ©
程式碼之家 All Rights Reserved