#include <stdio.h> #include <stdlib.h> typedef struct Node { int value; struct Node* next; } Node; Node* buyNewNode() { Node* newnode = (Node*)malloc(sizeof(Node)); newnode->next = NULL; scanf("%d ", &(newnode->value)); return newnode; } Node* NodeInit() { Node* newnode = (Node*)malloc(sizeof(Node)); newnode->next = NULL; return newnode; } //用于输入数据-尾添 void tailPop(Node* head) { while (head->next != NULL) { head = head->next; } Node* newnode = buyNewNode(); head->next = newnode; } void del(Node* head, int num, int* last) { Node* now = head; Node* tmp = NULL; *last = 0; char flag = 0;//判断head是否找到要删除的数据 while (head->next != NULL) { head = head->next; (*last)++; while (head->value == num) { tmp = head; if (head->next != NULL) { head = head->next; } else if (head->next == NULL) { now->next = NULL; (*last)--; free(head); return; } free(tmp); flag = 1; } if (flag == 0) { now = head; } else { now->next = head; now = head; flag = 0; } } } void printNode(Node* head) { while (head->next != NULL) { head = head->next; printf("%d ", head->value); } printf("\n"); } int main() { int n, delnum, last;//last:剩余个数 Node* head = NodeInit(); scanf("%d", &n); for (int i = 0; i <= n - 1; i++) { tailPop(head); } scanf("%d", &delnum); del(head, delnum, &last); printf("%d\n", last); printNode(head); }
这道题的难点在于:
当删除最后一个节点时,上一个节点(非要删除的数字)的next应为NULL。
虽然free可以释放你删除的节点,但上一个节点的next仍保留着指针,在用node->next往下走时,会非法访问(因为你的节点已经free)。
所以就要使其next为NULL。