双向链表的基本操作

  • 我想你在看这之前已经掌握了单向链表了,如果对单向链表不是很了解,可以看看这篇文章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
代码写的很简洁,只为说明问题,有什么不好的地方,欢迎拍砖!(●'◡'●)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容