DBLinkList<T> 實作 IListDS<T> 介面,採用哨兵節點設計簡化邊界條件處理。雙向鏈表每個節點擁有 Prev 和 Next 兩個引用,使插入刪除操作需同時維護四個指標關係,複雜度較單向鏈表顯著提升。
private DBNode<T> header;
public DBLinkList()
{
header = new DBNode<T>();
header.Next = null;
header.Prev = null;
}
私有輔助方法,從頭節點向後遍歷至第 i 個位置,包含空表檢查與索引邊界驗證。
// 前插核心邏輯
current.Prev.Next = newNode;
newNode.Next = current;
newNode.Prev = current.Prev;
current.Prev = newNode;
斷開目標節點的前後連結,並清空其引用協助 GC 回收:
current.Prev.Next = current.Next;
current.Next.Prev = current.Prev;
current.Prev = null;
current.Next = null;
遍歷至尾節點直接掛載新節點,處理空表特殊情況。
count 欄位達到 O(1)header.Data == null 不可靠,應檢查 header.Next == nullArgumentOutOfRangeException 取代 Console.Write文末提及循環鏈表僅改變終止條件(判斷是否回到頭節點),核心操作邏輯大同小異,適合作為進階練習題目。