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

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

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

// #include <bits/stdc++.h>
#include <iostream>
#include <list>
using namespace std;
struct ListNode{
    int val;
    ListNode *next;
    ListNode():val(0), next(nullptr){}
    ListNode(int x): val(x), next(nullptr){}
    ListNode(int x, ListNode *nxt): val(x), next(nxt){}
};

ListNode* find_val(ListNode *head, int target){
    while(head->val != target && head){
        head = head->next;
    }
    return head;
}


int main() {
    int n, head;
    cin >> n >> head;
    ListNode *list_head = new ListNode(head);
    int insert_val, front_node_val;
    for(int i = 0; i < n - 1; i++){ // 挨个插入链表
        cin >> insert_val >> front_node_val;
        ListNode *insert_node = new ListNode(insert_val);
        ListNode *cur = find_val(list_head, front_node_val);
        insert_node -> next = cur -> next;
        cur -> next = insert_node;
    }
    int delete_val;
    cin >> delete_val;
    ListNode *dummy = new ListNode(0, list_head);
    ListNode *pre = dummy;
    while(pre -> next -> val != delete_val){
        pre = pre -> next;
    }
    ListNode *temp = pre->next;
    pre->next = pre->next->next;
    delete temp;
    list_head = dummy->next;
    while(list_head){
        cout << list_head->val << " ";
        list_head = list_head->next;
    }
    return 0;
}
// 64 位输出请用 printf("%lld")

其实可以使用STL容器中的forward list,使用find()函数找到节点,insert_after()在前面找到的节点后边插入,这样会更简便。但是既然是给自己练习用的,那就把链表那一套再练习练习,多写写熟练就好,有时候遇到题目比如链表部分翻转的ACM模式题目,也能更得心应手

全部评论

相关推荐

剑桥断刀:找啥工作,牛客找个比如大厂软开或者随便啥的高薪牛马,大把没碰过妹子的技术仔,狠狠拿捏爆金币
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务