c - 删除链表中的第一个节点
问题描述
我正在尝试删除链接列表中的第一个节点,但我不知道该怎么做。我的链接列表看起来像这样
typedef struct availableForRent{
int milage;
char plateNum[8];
struct availableForRent * next;
} availablreForRent;
我的链表的初始节点是硬编码的,就像这样
struct availableForRent * head = NULL;
head = malloc(sizeof(struct availableForRent));
head->milage = 190000;
fillString(head->plateNum);
head->next = NULL;
fillString 只是获取用户输入并将其放入数组中
我通过这样的推送功能将成员添加到我的列表中
void pushAvailable(struct availableForRent * head) {
struct availableForRent * current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = malloc(sizeof(struct availableForRent));
printf("Enter a milage amount: ");
scanf("%d", ¤t->next->milage);
fillString(current->next->plateNum);
current->next->next = NULL;
}
我删除第一个成员的功能如下所示
struct availableForRent * next_node = *head;
if (next_node->next == NULL) {
printf("Cannot remove member as it is the only data in the list!\n");
return;
}
next_node = next_node->next;
free(*head);
*head = next_node;
当我运行我的程序时,我收到此错误消息,
rentalQ1(2799,0x7fff9d09b380) malloc: *** error for object 0x7ffee8f62a08: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6
这是否意味着我试图释放的节点不存在或其他什么?
解决方案
看来不分配 next_node 是我的问题。
next_node = malloc(sizeof(struct availableForRent));
推荐阅读
- python - 在python中将嵌套的JSON数据提取到Pandas Dataframe
- python - PyQt,设置特定数量的行编辑输入
- javascript - 用字母和数字组分割字符串
- php - MySQL:将 100 个随机数的列表插入一个字段然后显示它们
- javascript - 用于查找最高质数的 Javascript 程序
- ruby-on-rails - 对如何正确设置和使用关联感到困惑
- python - 为什么我从库 `stdlib_list` 中丢失了一个文件?
- asp.net-web-api - 401 未经授权使用 Javascript 访问 Web API
- jsoup - 使用 Jsoup 解析 HTML 以获取单个元素的文本
- python - 如何导入脚本?