题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct NODE{
int val;
struct NODE *next;
}node;
int main(){
int n;
scanf("%d", &n);
node *head = (node*)malloc(sizeof(node));
scanf("%d", &head->val);
head->next = NULL;
int val1, val2;
node *tmp = (node*)malloc(sizeof(node));
for(int i = 0; i < n - 1; i++){
scanf("%d %d", &val2, &val1);
tmp = head;
while(tmp){
if(tmp->val == val1){
node *nod = (node*)malloc(sizeof(node));
nod->val = val2;
nod->next = tmp->next;
tmp->next = nod;
break;
}
tmp = tmp->next;
}
}
int val_d;
scanf("%d", &val_d);
tmp = head;
if(tmp->val == val_d){
head = tmp->next;
free(tmp);
}else{
while(tmp->next){
if(tmp->next->val == val_d){
node *to_delete = tmp->next;
tmp->next = to_delete->next;
free(to_delete);
break;
}
tmp = tmp->next;
}
}
tmp = head;
while(tmp){
printf("%d ", tmp->val);
tmp = tmp->next;
}
return 0;
}