链表的插入与删除操作/C++

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

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

#include<iostream>
#include<string>
#include<sstream>
#include<vector>
#include <algorithm>
#include <unordered_map>
#include <iomanip>
#include <math.h>
#include <deque>
#include <queue>
#include <stack>

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 *next) : val(x), next(next) {}
  };


 // 找到值为a的节点,将值为b的节点插进去
ListNode* insetNode(ListNode* dummy, int a, int b){
    ListNode * tmp = dummy->next;
    while(tmp != nullptr){
        if(tmp->val == a){
            tmp->next =  new ListNode(b, tmp->next);
            return dummy;
        }
        tmp = tmp->next;
    }
     return  dummy;
}

ListNode* deleteNode(ListNode* dummy, int del_node){
    ListNode* tmp = dummy;
    while(tmp != nullptr &&tmp->next != nullptr){
        if(tmp->next->val == del_node){
            tmp->next = tmp->next->next;
        }
        tmp = tmp->next;
    }
    return dummy;
}

void showList(ListNode* dummy){
    ListNode*  tmp = dummy->next;
    while(tmp!= nullptr){
        cout<<tmp->val<<" ";
        tmp = tmp->next;
    }
    cout<<endl;
}


int main()
{
    int n;
    while(cin >>n){
        ListNode* dummy = new ListNode(0);

        // 输入头节点
        int p;
        cin>>p;
        dummy->next = new ListNode(p);

        // 输入每个节点
        int a, b;
        for(int i = 0; i < n-1; i++){
            cin>>a>>b;
            dummy = insetNode(dummy, b, a);
        }
//        showList(dummy);

        int del_node;
        cin>>del_node;

        dummy = deleteNode(dummy, del_node);

        showList(dummy);
    }

}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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