题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
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)); //node *tmp = (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); node *tmp2; tmp2 = head; tmp = head->next; while(tmp2){ if(tmp->val == val_d){ tmp2->next = tmp->next; tmp = tmp2->next; break; } else tmp = tmp->next; tmp2 = tmp2->next; } if(head->val == val_d){ tmp = head->next; head = tmp; } while(head){ printf("%d ", head->val); head = head->next; } return 0; }