【发布时间】:2017-10-01 10:03:39
【问题描述】:
我在练习链表:
即使在使用deleteList() 函数删除列表后,我的printList() 函数仍在打印整个列表,这是我的代码,我的代码有什么问题?是删除函数声明还是函数调用有问题,我的main()和printList()函数有什么错误吗?
我在互联网上搜索并尝试了教程网站上的代码。
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} node;
void deleteList(node **head);
void printList(node *head);
int main(void) {
node *prev, *head, *p;
head = NULL;
for (int i = 0; i < 5; i++) {
p = malloc(sizeof(node));
printf("Enter number\n");
scanf("%i", &p->data);
p->next = NULL;
if (head == NULL)
head = p;
else
prev->next = p;
prev = p;
}
deleteList(&head);
printList(head);
free(p);
return 0;
}
void printList(node *head) {
if (head == NULL) {
printf("\nNULL\n");
} else {
printf("\n%i", head->data);
printList(head->next);
}
}
void deleteList(node **head) {
node *cur = *head;
node *nxt;
while (cur != NULL) {
nxt = cur->next;
free(cur);
cur = nxt;
}
*head = NULL;
}
【问题讨论】:
-
你确定吗?它对我显示为空
-
添加deleteListe后是否重新编译了代码?
-
free(p);似乎双倍释放(最后分配的p值存储为列表的一部分)并导致 UB。您应该将p设为本地循环。
标签: c linked-list