首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 雙向鏈結清單模擬瀏覽器前進/後退功能 (一) - 資料結構設計

     編輯:關於C語言

瀏覽器歷史導航的核心資料結構是雙向鏈結清單。本文從行為分析出發,設計 HistoryItem 資料類別與 HistoryManager 管理類別,奠定後續實作基礎。

行為分析:IE/Chrome 歷史邏輯

  1. 造訪 A → B → C → D:歷史 = [A, B, C, D],當前 = D。
  2. 後退到 B:當前 = B,歷史不變。
  3. 在 B 造訪 E:C、D 被移除,歷史 = [A, B, E],當前 = E。

此行為要求:

  • O(1) 在尾端新增。
  • O(1) 移除當前節點之後的所有節點。
  • O(1) 向前/向後移動當前指標。

LinkedList<T> (雙向鏈結清單) 完美滿足所有需求。

HistoryItem 資料類別


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;
    }
}

HistoryManager 核心骨架


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> + 索引?

操作List<T> + IndexLinkedList<T>
新增 (移除尾端後)O(n) 移除 + O(1) AddO(1) RemoveLast + O(1) AddLast
前進/後退O(1) Index ±= 1O(1) Node.Next/Previous
記憶體連續陣列,擴容需複製節點分散,無擴容開銷

雖然索引版寫法較直觀,但 LinkedList 在頻繁修改尾端時效能更穩定,且語意上「當前節點」直接對應 LinkedListNode,程式碼更清晰。

下一步

下一篇將實作完整的 HistoryManager 並整合至 WinForms/WebForms 介面,處理按鈕啟用狀態同步與頁面載入邏輯。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved