题解 | #【模板】链表#
【模板】链表
https://www.nowcoder.com/practice/97dc1ac2311046618fd19960041e3c6f
#include<iostream>
using namespace std;
class List{
private:
struct ListNode{
int val;
ListNode* next;
ListNode(int n):val(n),next(NULL){}
};
ListNode* head=NULL;
public:
List(){}
void m_insert(int x,int y){
ListNode* res=new ListNode(0);
res->next=head;
ListNode* pre=res;
ListNode* cur=head;
while(cur!=NULL){
if(cur->val==x){
ListNode* newnode=new ListNode(y);
newnode->next=cur;
pre->next=newnode;
break;
}
pre=cur;
cur=cur->next;
}
if(cur==NULL){
ListNode* newnode=new ListNode(y);
newnode->next=cur;
pre->next=newnode;
}
head=res->next;//更新头节点
free(res);
}
void m_delete(int x){
ListNode* res=new ListNode(0);
res->next=head;
ListNode* pre=res;
ListNode* cur=head;
while(cur!=NULL){
if(cur->val==x){
pre->next=cur->next;
}
pre=cur;
cur=cur->next;
}
head=res->next;
free(res);
}
void print(){
ListNode* cur=head;
while(cur!=NULL){
cout<<cur->val<<' ';
cur=cur->next;
}
}
};
int main(){
int n;
cin>>n;
string str;
List li;
for(int i=0;i<n;i++){
cin>>str;
int x,y;
if(str=="insert"){
cin>>x>>y;
li.m_insert(x,y);
}
if(str=="delete"){
cin>>x;
li.m_delete(x);
}
}
li.print();
}