Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

雙向鏈表 C++ 實作:前驅指標帶來的設計差異

雙向鏈表與單鏈表最大的不同,在於每個節點多了一個前驅指標。看似只是多存一個位址,卻讓刪除操作從「必須先找到前驅」變成「直接改兩邊的指標」,也讓反向遍歷成為可能。相對的,所有插入刪除函式都要多維護一條 prev 鏈,實作上必須更小心。

一、List.h

typedef int DataType;

// 節點類(建議寫法:struct 成員預設 public)
struct LinkNode
{
    LinkNode(const DataType x);
    DataType _data;      // 節點資料
    LinkNode* _next;     // 後繼指標
    LinkNode* _prev;     // 前驅指標
};

class List
{
public:
    List();                                   // 構造
    List(const List& s);                       // 拷貝構造
    List& operator=(List& s);                  // 賦值運算子重載
    ~List();

public:
    void Reverse();                           // 逆置
    void Swap(List& s);                        // 交換
    void PrintSList();                        // 列印
    void PushBack(const DataType& x);          // 尾插
    void Clear();                             // 置空
    void PopBack();                           // 尾刪
    void PushFront(DataType x);               // 頭插
    void PopFront();                          // 頭刪
    void Insert(LinkNode* pos, DataType x);   // 定位置插入
    void Erase(LinkNode* pos);                // 刪除指定節點
    LinkNode* Find(DataType x);               // 查找
    int Amount();                             // 節點個數
    void Remove(DataType x);                  // 查找並刪除

private:
    LinkNode* _head;    // 頭指標
    LinkNode* _tail;    // 尾指標
};

二、構造、賦值與解構

LinkNode::LinkNode(const DataType x)
    : _data(x), _next(NULL), _prev(NULL)
{}

List::List()
    : _head(NULL), _tail(NULL)
{}

List::List(const List& s)             // 拷貝構造
    : _head(NULL), _tail(NULL)
{
    if (s._head == NULL) return;

    LinkNode* tmp = s._head;
    while (tmp)
    {
        PushBack(tmp->_data);
        tmp = tmp->_next;
    }
}

// 賦值運算子(推薦寫法):交換指標即可,資源交給臨時物件收尾
List& List::operator=(List & s)
{
    if (this != &s)
    {
        swap(_head, s._head);
        swap(_tail, s._tail);
    }
    return *this;
}

List::~List()
{
    Clear();
}

三、尾插、頭插與置空

void List::PushBack(const DataType& x)
{
    if (_head == NULL)                // 空表:_head 與 _tail 同為新節點
    {
        _head = new LinkNode(x);
        _tail = _head;
    }
    else
    {
        _tail->_next = new LinkNode(x);
        _tail->_next->_prev = _tail;   // 關鍵:回填新節點的 prev
        _tail = _tail->_next;
    }
}

void List::PushFront(DataType x)
{
    if (_head == NULL) { PushBack(x); return; }

    LinkNode* tmp = _head;
    _head = new LinkNode(x);
    _head->_next = tmp;
    tmp->_prev = _head;               // 原頭節點的 prev 指向新頭
}

void List::Clear()
{
    LinkNode* begin = _head;
    while (begin != _tail)
    {
        _head = _head->_next;
        delete begin;
        begin = _head;
    }
    _head = NULL;
    _tail = NULL;
}

四、尾刪與頭刪:雙向鏈表的真正優勢

void List::PopBack()
{
    if (_head == NULL)
    {
        cout << "This List is empty !" << endl;
    }
    else if (_head == _tail)
    {
        delete _head;
        _head = _tail = NULL;
    }
    else
    {
        LinkNode* cur = _head;
        while (cur->_next != _tail)   // 仍可遍歷找前驅
            cur = cur->_next;
        delete _tail;
        _tail = cur;
        _tail->_prev = cur->_prev;
        _tail->_next = NULL;
    }
}

void List::PopFront()
{
    if (_head == NULL)
    {
        cout << "This List is empty !" << endl;
        return;
    }
    LinkNode* tmp = _head;
    _head = _head->_next;
    _head->_prev = NULL;              // 新頭沒有前驅
    delete tmp;
}

若額外保存尾節點的前驅,PopBack 也能做到 O(1);這裡保留遍歷寫法以對照單鏈表版本。

五、定位置插入與刪除

void List::Insert(LinkNode* pos, DataType x)
{
    assert(pos);
    if (pos == _tail) { PushBack(x); return; }

    LinkNode* tmp = new LinkNode(x);
    tmp->_next = pos->_next;
    pos->_next = tmp;
    tmp->_next->_prev = tmp;          // 後節點回指新節點
    tmp->_prev = pos;                 // 新節點指向 pos
}

void List::Erase(LinkNode* pos)
{
    assert(pos);
    if (pos == _tail)      { PopBack();  return; }
    else if (pos == _head){ PopFront(); return; }

    // 雙向鏈表的精髓:兩行搞定,不需搜尋前驅
    pos->_prev->_next = pos->_next;
    pos->_next->_prev = pos->_prev;
    delete pos;
}

對比單鏈表版本,Erase 少了整段找前驅的迴圈——這正是雙向結構最直接的收益。

六、查找、計數與刪除指定值

LinkNode* List::Find(DataType x)
{
    if (_head == NULL)
    {
        cout << "This List is empty !" << endl;
        return NULL;
    }
    LinkNode* tmp = _head;
    while (tmp != NULL)
    {
        if (tmp->_data == x) return tmp;
        tmp = tmp->_next;
    }
    return NULL;
}

int List::Amount()
{
    if (_head == NULL) return 0;

    int count = 0;
    LinkNode* cur = _head;
    while (cur != _tail)
    {
        count++;
        cur = cur->_next;
    }
    return ++count;
}

void List::Remove(DataType x)
{
    if (_head == NULL)
    {
        cout << "This List is empty !" << endl;
        return;
    }
    LinkNode* tmp = Find(x);
    if (tmp != NULL) Erase(tmp);
}

七、逆置的三種寫法

void List::Reverse()
{
    if (_head == NULL || _head == _tail) return;
    int ret = Amount();

    // 方法一:以頭插方式重建整條鏈表(直觀但配置頻繁)

    // 方法二:只交換對稱位置節點的資料(高效,推薦)
    LinkNode* begin = _head;
    LinkNode* end = _tail;
    while (ret)
    {
        if (end->_next == begin) break;      // 兩指標相遇
        ret /= 2;                          // 只需走一半
        swap(begin->_data, end->_data);
        begin = begin->_next;
        end = end->_prev;                  // 反向走,靠 prev
    }

    // 方法三:交換每個節點的 prev 與 next,再對調 head/tail
}

方法二之所以能只走一半,正是因為有 _prev 可以從尾往頭走;方法三則是最省時的指標操作版,實作時注意迴圈條件要判斷 cur != NULL 以免走過頭。

八、測試

void Test1()
{
    List list1;
    for (int i = 1; i <= 6; ++i) list1.PushBack(i);
    list1.PrintSList();

    List list2 = list1;                 // 賦值運算子
    list2.PrintSList();

    list2.Reverse();
    list2.PrintSList();

    // list2.Erase(list2.Find(5));
    // list2.Insert(list2.Find(2), 0);
    // list2.Remove(3);
}

int main()
{
    Test1();
    system("pause");
}

重點回顧

雙向鏈表的每一個操作,本質上都在維護兩條對稱的鏈:新增節點要同時接好 prev 與 next、刪除節點要同時修好前後兩邊、頭節點的 prev 與尾節點的 next 一律為 NULL。把這三條對稱性守住,雙向鏈表就比單鏈表更好用,也更難寫錯。

Copyright © Linux教程網 All Rights Reserved