ACM面试题之算法知识编程语言爱好者

双向链表的基本操作

2016-06-15  本文已影响940人  sugar_coated

节点的编写

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
代码写的很简洁,只为说明问题,有什么不好的地方,欢迎拍砖!(●'◡'●)
上一篇 下一篇

猜你喜欢

热点阅读