双向链表的基本操作

  • 我想你在看这之前已经掌握了单向链表了,如果对单向链表不是很了解,可以看看这篇文章o( ̄▽ ̄)ブ。http://www.jianshu.com/p/1b6309b6c9ab

    双向链表也叫双链表,是链表的一种,它的每个数据结点中都有两个指针,分别指向直接后继和直接前驱。所以,从双向链表中的任意一个结点开始,都可以很方便地访问它的前驱结点和后继结点。

节点的编写

struct node {
    int val;//节点中存的值
    node *prior;//前驱结点
    node *next;
};

双链表的创建

node *creat( ) {
    node *head = nullptr, *tail;
    int num;
    while(cin >> num && num) {//以输入0结束创建
        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;//用于标记是否删除过,使可以删除连续相同的两个节点
        if(pNode->next->val == num) {
            flag = 1;//表示删除过
            node *dNode = pNode->next;
            pNode->next = dNode->next;
            if(dNode->next)//最后一个节点的next为nullptr,是没有前驱的
                dNode->next->prior = pNode;
            delete dNode;
            //如果删除一个,就加break;
        }
        if(!flag && pNode->next)//删除过就不需要更新pNode,因为在删除前已经更新过pNode了
            pNode = pNode->next;
    }
}

测试

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

struct node {
    int val;
    node *prior;//前驱结点
    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.jianshu.com/p/1b6309b6c9ab)
代码写的很简洁,只为说明问题,有什么不好的地方,欢迎拍砖!(●'◡'●)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值