题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
#include <iostream>
#include <list>
using namespace std;
class llist{
public:
int num;
llist* next;
void add(llist &in){
in.next=this->next;
this->next=∈
}
void del(){
if(this->next!=nullptr){
llist *temp = this->next;
this->next=this->next->next;
delete temp;
}
else{
delete this->next;
this->next=nullptr;
}
}
llist(int in):num(in),next(nullptr){}
};
int main() {
int a;
while (cin >> a) { // 注意 while 处理多个 case
int first,b,c;
cin>>first;
llist *lt = new llist(first);
for(int i=0;i<a-1;++i){
llist* temp = lt;
cin>>b>>c;
while(temp!=nullptr){
if(temp->num == c){
llist *temp1 = new llist(b);
temp->add(*temp1);
break;
}
temp=temp->next;
}
}
int del;
cin>>del;
llist* temp = lt;
while (temp!=nullptr) {
if(temp->next!=nullptr && temp->next->num == del){
temp->del();
break;
}
temp=temp->next;
}
while (lt!=nullptr){
llist* temp = lt;
cout<<lt->num<<' ';
lt=lt->next;
delete temp;
}
}
return 0;
}
// 64 位输出请用 printf("%lld")
查看14道真题和解析