题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
#include<iostream>
#include<vector>
using namespace std;
struct ListNode{
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr){}
};
ListNode* Delete_node(ListNode* head, int val){
ListNode* dummyhead = new ListNode(0);
dummyhead->next = head;
ListNode* cur = dummyhead;
while(cur!=nullptr){
if(cur->next->val==val){
cur->next=cur->next->next;
return head;
}
cur=cur->next;
}
return head;
}
int main() {
int num;//节点数
cin>>num;
int head; //头节点值
cin>> head;
ListNode* headnode = new ListNode(head);
int follow;
int front;
vector<ListNode*> nodes;
nodes.push_back(headnode);
for(int i=0; i<2*(num-1); i+=2){
cin>>follow>>front;
ListNode* node_next = new ListNode(follow);
int j=0;
while(nodes[j]->val != front && j<nodes.size()){
j++;
}
ListNode* buff = nodes[j]->next;
nodes[j]->next= node_next;
node_next->next = buff;
nodes.push_back(node_next);
}
int del_val;
cin>> del_val;
headnode = Delete_node(headnode, del_val);
//output
//
ListNode* cur=headnode;
while(cur!=nullptr){
cout<<cur->val<<" ";
cur=cur->next;
}
return 0;
}
// 64 位输出请用 printf("%lld")