雙向鏈表的基本操作

  • 我想你在看這之前已經(jīng)掌握了單向鏈表了,如果對單向鏈表不是很了解,可以看看這篇文章o( ̄▽ ̄)ブ。
    http://www.itdecent.cn/p/1b6309b6c9ab

    雙向鏈表也叫雙鏈表,是鏈表的一種,它的每個數(shù)據(jù)結(jié)點中都有兩個指針,分別指向直接后繼和直接前驅(qū)。所以,從雙向鏈表中的任意一個結(jié)點開始,都可以很方便地訪問它的前驅(qū)結(jié)點和后繼結(jié)點。

節(jié)點的編寫

struct node {
    int val;//節(jié)點中存的值
    node *prior;//前驅(qū)結(jié)點
    node *next;
};

雙鏈表的創(chuàng)建

node *creat( ) {
    node *head = nullptr, *tail;
    int num;
    while(cin >> num && num) {//以輸入0結(jié)束創(chuàng)建
        node *pNode = new node;
        pNode->val = num;
        if(!head) {
            head = pNode;
            head->prior = nullptr;
            head->next = nullptr;
            tail = head;
            continue;
        }
        pNode->prior = tail;
        pNode->next = nullptr;
        tail->next = pNode;
        tail = pNode;
    }
    return head;
}

鏈表的輸出

void output(node *head) {
    if(!head) return ;
    for(node *pNode = head; pNode; pNode = pNode->next)
        cout << pNode->val << " ";
    cout << endl;
}

刪除 (刪除多個或一個)

void remove(node *head, const int num) {
    if(!head) return ;
    node *pNode = head;
    while(pNode->next) {
        bool flag = 0;//用于標(biāo)記是否刪除過,使可以刪除連續(xù)相同的兩個節(jié)點
        if(pNode->next->val == num) {
            flag = 1;//表示刪除過
            node *dNode = pNode->next;
            pNode->next = dNode->next;
            if(dNode->next)//最后一個節(jié)點的next為nullptr,是沒有前驅(qū)的
                dNode->next->prior = pNode;
            delete dNode;
            //如果刪除一個,就加break;
        }
        if(!flag && pNode->next)//刪除過就不需要更新pNode,因為在刪除前已經(jīng)更新過pNode了
            pNode = pNode->next;
    }
}

測試

#include <iostream>
#include <cstdio>
using namespace std;

struct node {
    int val;
    node *prior;//前驅(qū)結(jié)點
    node *next;
};
int main() {
    node *head = nullptr;
    head = creat();
    output(head);
    
    int num;
    cin >> num;
    remove(head, num);
    output(head);
    
    return 0;
}

C++11編譯通過(/▽\=)

Paste_Image.png

插入等基本操作與單鏈表相似,這里就不多說了,你懂的(http://www.itdecent.cn/p/1b6309b6c9ab
代碼寫的很簡潔,只為說明問題,有什么不好的地方,歡迎拍磚!(●'?'●)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容