瀏覽器歷史導航的核心資料結構是雙向鏈結清單。本文從行為分析出發,設計 HistoryItem 資料類別與 HistoryManager 管理類別,奠定後續實作基礎。
此行為要求:
LinkedList<T> (雙向鏈結清單) 完美滿足所有需求。
public class HistoryItem
{
public string Title { get; set; }
public string Html { get; set; }
public string Url { get; set; }
public HistoryItem() { }
public HistoryItem(string title, string html, string url)
{
Title = title; Html = html; Url = url;
}
}
public class HistoryManager
{
private readonly LinkedList _history = new LinkedList();
private LinkedListNode _current;
public HistoryItem Current => _current?.Value;
public bool CanBack => _current?.Previous != null;
public bool CanForward => _current?.Next != null;
public void Add(HistoryItem item)
{
// 1. 若有前進歷史,全部移除
if (_current != null)
{
while (_current.Next != null)
_history.RemoveLast();
}
// 2. 新增至尾端並更新當前
_current = _history.AddLast(item);
}
public void Back() => _current = _current?.Previous;
public void Forward() => _current = _current?.Next;
}
| 操作 | List<T> + Index | LinkedList<T> |
|---|---|---|
| 新增 (移除尾端後) | O(n) 移除 + O(1) Add | O(1) RemoveLast + O(1) AddLast |
| 前進/後退 | O(1) Index ±= 1 | O(1) Node.Next/Previous |
| 記憶體 | 連續陣列,擴容需複製 | 節點分散,無擴容開銷 |
雖然索引版寫法較直觀,但 LinkedList 在頻繁修改尾端時效能更穩定,且語意上「當前節點」直接對應 LinkedListNode,程式碼更清晰。
下一篇將實作完整的 HistoryManager 並整合至 WinForms/WebForms 介面,處理按鈕啟用狀態同步與頁面載入邏輯。