题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
#include <stdio.h> #include<stdlib.h> typedef struct STLNode { int data; struct STLNode* next; }STLNode; void InsertAfter(STLNode** pphead,int x,int pos)//指定数值后面插入 { STLNode* head=*pphead; STLNode* newnode=(STLNode*)malloc(sizeof(STLNode)); newnode->data=x; if(head==NULL) { head=newnode; head->next=NULL; return; } while(head->data!=pos) { head=head->next; } newnode->next=head->next; head->next=newnode; return; } void Erase(STLNode** pphead,int del)//删除指定数值节点 { STLNode* pre=*pphead; STLNode* cur=*pphead; if(pre->data==del) { *pphead=pre->next; free(pre); return; } while(pre->next->data!=del) { pre=pre->next; } cur=pre->next; pre->next=cur->next; free(cur); cur=NULL; return; } void Print(STLNode* phead)//打印链表 { while(phead!=NULL) { printf("%d ",phead->data); phead=phead->next; } return; } int main() { int i=0,n=0,x=0,del,arr[1000][2]; STLNode* plist=(STLNode*)malloc(sizeof(STLNode)); scanf("%d %d",&n,&x); plist->data=x; plist->next=NULL; for(i=1;i<n;i++) { scanf("%d %d",&arr[i][0],&arr[i][1]); InsertAfter(&plist,arr[i][0],arr[i][1]); } scanf("%d",&del); Erase(&plist,del); Print(plist);//题目当中省略了销毁链表和释放动态内存等,可自行添加 return 0; }