题解 | #从单向链表中删除指定值的节点#

从单向链表中删除指定值的节点

https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f

#include<iostream>
#include<unordered_map>
#include<vector>
using namespace std;
struct DlinkedNode{

    int val;
    DlinkedNode* pre;
    DlinkedNode* next;
    DlinkedNode(): val(0), pre(nullptr), next(nullptr){};
    DlinkedNode(int v): val(v),pre(nullptr),next(nullptr){};

};

int main(){
    unordered_map<int, DlinkedNode*> cache;
    string tmp;
    vector<int> inputs;
    while(getline(cin,tmp,' ')){
        inputs.push_back(stoi(tmp));        
    }
    int n = inputs[0];
    int first_val = inputs[1];
    DlinkedNode* head = new DlinkedNode();
    DlinkedNode* tail = new DlinkedNode();
    DlinkedNode* first = new DlinkedNode(first_val);
    cache[first_val] = first;
    head->next = first;
    first->pre = head;
    first->next = tail;
    tail -> pre = first;
    for(int i = 2; i < inputs.size()-1; i+=2){
//         cout << "cur i :" << i << endl;
        int back_val = inputs[i];
        int front_val = inputs[i+1];
//         cout << "front_val : " << front_val << endl;
//         cout << "back_val : " << back_val << endl;
        DlinkedNode* back_node = new DlinkedNode(back_val);
        cache[back_val] = back_node;
        DlinkedNode* front_node = cache[front_val];

        // 插入节点
        back_node->next = front_node->next;
        front_node->next->pre = back_node;
        back_node->pre = front_node;
        front_node->next = back_node;

    }

    DlinkedNode* cur = head;
    while(cur){
        if( cur->val == inputs.back() ){
            cur->pre->next = cur->next;
            cur->next->pre = cur->pre;
            break;
        }
        cur = cur->next;
    }

    DlinkedNode* res = head->next;
    if(res == tail)
        cout << "nullptr" << endl;
    while(res!=tail){
        cout << res->val << ' ';
        res = res->next;
    }


}
全部评论

相关推荐

点赞 评论 收藏
分享
05-07 19:10
已编辑
中国科学技术大学 C++
silly01:现在先去 momenta,8-9月去鹅找日常实习,八股文算法背好了你这随便进。不过建议补充一下后端知识,MySQL、Redis看下八股,再补个6824,加点go后台的技术栈,9月随便进大厂。CPP后端只能来WXG
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务