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

摘要
Title: HJ48 从单向链表中删除指定值的节点
Tag: 链表、单向链表
Memory Limit: 64 MB
Time Limit: 1000 ms

Powered by:NEFU AB-IN

Link

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

  • 题意

    输入一个单向链表和一个节点的值,从单向链表中删除等于该值的节点,删除后如果链表中无节点则返回空指针。

  • 思路

    单向链表的题,涉及到了 在 指定元素后面插入值删除指定元素
    可以利用 stl 模板类 forward_list

    科普一下: image

  • 代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    #include <algorithm>
    #include <bits/stdc++.h>
    #include <cctype>
    #include <cstdio>
    #include <queue>
    #include <sstream>
    #include <vector>
    using namespace std;
    #define int long long
    #undef int

    #define SZ(X) ((int)(X).size())
    #define ALL(X) (X).begin(), (X).end()
    #define IOS \
    ios::sync_with_stdio(false); \
    cin.tie(nullptr); \
    cout.tie(nullptr)
    #define DEBUG(X) cout << #X << ": " << X << '\n'

    const int N = 30, INF = 0x3f3f3f3f;
    typedef pair<int, int> PII;


    signed main() {
    // freopen("Tests/input_1.txt", "r", stdin);
    IOS;

    int n, head;
    cin >> n >> head; //输入结点数和头结点的值
    forward_list<int> linklist; //创建一个单向链表
    linklist.push_front(head); //初始化头结点
    for (int i = 1; i < n; i++) {
    int front, back;
    cin >> back >> front;
    auto it = find(linklist.begin(), linklist.end(), front);
    linklist.insert_after(it, back); //逐个插入结点
    }
    int last;
    cin >> last; //输入要删除的结点值
    linklist.remove(last); //移除具有该值的节点
    for (auto it : linklist) {
    cout << it << " "; //从头到尾输出链表的值
    }


    return 0;
    }
使用搜索:谷歌必应百度