题解 | #从单向链表中删除指定值的节点#C++哈希map

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

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

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

struct ListNode {
    int val;
    ListNode* next;
    ListNode() : val(0), next(nullptr) {};
    ListNode(int v) : val(v), next(nullptr) {}
};

void print(ListNode* dummy) {
    ListNode* p = dummy;
    while (p->next) {
        p = p->next;
        cout << p->val << " ";
    }
    cout << endl;
}

int main() {
    int num; // 链表结点个数
    int head_val; // 头结点值
    cin >> num >> head_val;
    int i_val;
    int pre_val;
    auto dummuy = new ListNode(-1);
    auto head = new ListNode(head_val);
    dummuy->next = head;
    unordered_map<int, ListNode*> m;
    m[-1] = dummuy;
    m[head_val] = head;

    for (int i = 0; i < num - 1; ++i) {
        cin >> i_val >> pre_val;
        auto p = m[pre_val];
        auto newNode = new ListNode(i_val);
        if (p) newNode->next = p->next;
        p->next = newNode;
        m[i_val] = newNode;
    }
    int del_val;
    cin >> del_val;
    auto p = m[del_val];
    if (p == head) {
        dummuy->next = p->next;
    } else if (p->next == nullptr) {
        p = nullptr;
    } else {
        p->val = p->next->val;
        p->next = p->next->next;
    }
    print(dummuy);
    return 0;
}

全部评论

相关推荐

点赞 评论 收藏
分享
感性的干饭人在线蹲牛友:🐮 应该是在嘉定这边叭,禾赛大楼挺好看的
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务