题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
#include <stdio.h> #include <stdlib.h> typedef struct linkedList { int val; struct linkedList *next; } Node; void insertNode(Node *head, int val, int aim) { while(head != NULL) { if(head->val == aim) { Node *temp = (Node *)malloc(sizeof(Node)); temp->val = val; temp->next = head->next; head->next = temp; return; } head = head->next; } } void delNode(Node **head, int aim) { if((*head)->val == aim) { Node *temp = (*head)->next; free(*head); *head = temp; } Node *iter = *head; while(iter->next != NULL) { if(iter->next->val == aim) { Node *temp = iter->next; iter->next = temp->next; free(temp); return; } iter = iter->next; } } void printList(Node *head) { while(head->next != NULL) { printf("%d ", head->val); head = head->next; } printf("%d\n", head->val); } void freeList(Node *head) { while(head != NULL) { Node *temp = head->next; free(head); head = temp; } } int main() { int num, headVal, delVal; // 读入输入中的节点数量注意数量包括头节点 scanf("%d %d", &num, &headVal); // 定义头节点 Node *head = (Node *)malloc(sizeof(Node)); head->val = headVal; head->next = NULL; // 插入节点 for(int i = 0; i < num - 1; i++) { int val; int aim; scanf("%d %d", &val, &aim); insertNode(head, val, aim); } // 删除节点 scanf("%d", &delVal); delNode(&head, delVal); printList(head); freeList(head); }