题解 | #【模板】链表#
【模板】链表
https://www.nowcoder.com/practice/97dc1ac2311046618fd19960041e3c6f
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct a{ int data; struct a *next; }arr; //插入 void input(arr **head,int x,int y){ arr *phead=*head,*pphead=*head,*zzz; if(*head==NULL){ phead=(arr*)calloc(1,sizeof(arr)); phead->data=y; phead->next=NULL; *head=phead; }else { while(pphead){ if(pphead->data==x){ break; }else{ phead=pphead; pphead=pphead->next; } } if(pphead==*head){ zzz=(arr*)calloc(1,sizeof(arr)); zzz->data=y; zzz->next=pphead; *head=zzz; }else{ zzz=(arr*)calloc(1,sizeof(arr)); zzz->data=y; zzz->next=pphead; phead->next=zzz; } } } //删除 void delete(arr **head,int x){ arr* phead=*head,*pphead=*head,*zzz; while(pphead){ if(pphead->data==x){ //删 if(pphead==*head){ *head=pphead->next; free(pphead); break; }else{ zzz=pphead->next; phead->next=zzz; free(pphead); break; } }else{ phead=pphead; pphead=pphead->next; } } } int main() { int n,x,y; char handle[7]; arr *head=NULL; scanf("%d",&n); for(int i=0;i<n;i++){ scanf("%s",handle); if(strcmp(handle,"insert")==0){ scanf("%d%d",&x,&y); input(&head,x,y); }else if(strcmp(handle,"delete")==0){ scanf("%d",&x); delete(&head,x); } } if(head==NULL){ printf("NULL"); }else { while(head){ printf("%d ",head->data); head=head->next; } } return 0; }