题解 | #【模板】链表#
【模板】链表
https://www.nowcoder.com/practice/97dc1ac2311046618fd19960041e3c6f
#include<bits/stdc++.h>
using namespace std;
struct Lnode{
int data;
Lnode *next;
};
void indexinsert(int a,int b,Lnode* L){
Lnode*p=L;
Lnode*q=p->next;
while(q!=NULL){
if(q->data==a){//这个地方如果是while则一个break跳不出两个while达不到目的
break;
}
p=q;//可以换成p=p->next;但我觉得就这样挺好
q=q->next;
}
Lnode *t=new Lnode;
t->data=b;
p->next=t;//在pq之间存下t结点
t->next=q;
}
void indexdel(int x,Lnode* L){
Lnode*p=L;
Lnode*q=p->next;
while(q!=NULL){
if(q->data==x){
p->next=q->next;//这个地方是删除一个节点是固定的语句
q->next=NULL;
delete q;
return;
// p=p->next;
// q=q->next;
// break;
}
else{
p=q;
q=q->next;
}
}
}
int main(){
Lnode *L=new Lnode;
L->next=NULL;
int n;
cin>>n;
for(int i=0;i<n;i++){
string op;
cin>>op;
if(op=="insert"){
int a,b;
cin>>a>>b;
indexinsert(a,b,L);
}
if(op=="delete"){
int x;
cin>>x;
indexdel(x,L);
}
}
Lnode *p=L->next;
if(p==NULL) cout<<"NULL"<<endl;
while(p!=NULL){
cout<<p->data<<" ";
p=p->next;
}
return 0;
}
/*
5
insert 0 1
insert 0 3
insert 1 2
insert 3 4
delete 4
output:
2 1 3
*/


查看9道真题和解析