题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
#include<stdio.h> #include<stdlib.h> typedef struct Link { int elem; struct Link* next; }link; void insert(link* head, int insertdata, int aimdata) { link *p=head; link* temp = (link*)malloc(sizeof(link)); temp->elem=insertdata; temp->next=NULL; while(p!=NULL) { if(p->elem==aimdata) { temp->next=p->next; p->next=temp; return; } p=p->next; } } link* delete(link* head,int aimdata) { link *p=head; if(head->elem==aimdata) { head=head->next; free(p); p=head; } if(head==NULL) return head; link *pold; pold=p; p=p->next; while(p!=NULL) { if(p->elem==aimdata) { pold->next=p->next; free(p); p=pold->next; } pold=p; p=p->next; } return head; } void display(link *head) { link *p=head; while(p!=NULL) { printf("%d ",p->elem); p=p->next; } return; } int main(void) { int n; int headdata; scanf("%d%d", &n,&headdata); link *head=(link*)malloc(sizeof(link)); head->elem=headdata; head->next=NULL; //链表插值 for (int i = 1; i < n; i++) { int insertdata; int aimdata; scanf("%d%d", &insertdata, &aimdata); insert(head,insertdata,aimdata); } //删除链表节点 int deletedata; scanf("%d",&deletedata); head=delete(head,deletedata); display(head); //释放内存 link *p=head; while(p->next!=NULL) { link *temp=p->next; free(p); p=temp; } return 0; }