c - 自由链表
问题描述
我有一个链表,我想删除它的所有节点。问题是,如果我调用 delete 它只会打印出 1 然后它会冻结。我读过一些其他类似的问题,但我不知道为什么会这样。我想我只是瞎了眼什么的。
#include <stdio.h>
#include <stdlib.h>
typedef struct _node {
int id;
struct _node *next;
} *node;
typedef struct {
node first;
} *head;
head newHead(node n) {
head h = malloc(sizeof(node));
h->first = n;
return h;
}
node newNode(int id) {
node n = malloc(sizeof(node));
n->id = id;
n->next = NULL;
return n;
}
void delete(head h) {
if(h->first == NULL) return;
node current = h->first;
while(current != NULL) {
printf("%i", current->id);
node tmp = current;
current = current->next;
free(tmp);
}
// free(h);
}
int main() {
node n = newNode(1);
head h = newHead(n);
node n2 = newNode(2);
node n3 = newNode(3);
node n4 = newNode(4);
n->next = n2;
n2->next = n3;
n3->next = n4;
printf("%i", h->first->id);
printf("%i", h->first->next->id);
printf("%i", h->first->next->next->id);
printf("%i", h->first->next->next->next->id);
delete(h);
return 0;
}
解决方案
在函数newNode
中,您分配的内存大小无效
node n = malloc(sizeof(node));
^^^^
这不是为类型的对象struct _node
分配内存,而是为指向此类对象的指针分配内存struct _node *
。
你需要写
node n = malloc(sizeof(struct _node));
`
并且您需要释放指针指向的内存h
。
该功能delete
可能看起来像
void delete( head *h )
{
for ( node current = ( *h )->first; current != NULL; )
{
printf("%i", current->id);
node tmp = current;
current = current->next;
free( tmp );
}
free( *h );
*h = NULL;
}
并称为
delete( &h );
在这种情况下,退出函数后指针h
将等于NULL
。
这是您更新的程序。
#include <stdio.h>
#include <stdlib.h>
typedef struct _node {
int id;
struct _node *next;
} *node;
typedef struct {
node first;
} *head;
head newHead(node n) {
head h = malloc(sizeof(node));
h->first = n;
return h;
}
node newNode(int id) {
node n = malloc(sizeof(struct _node));
n->id = id;
n->next = NULL;
return n;
}
void delete( head *h )
{
for ( node current = ( *h )->first; current != NULL; )
{
printf("%i", current->id);
node tmp = current;
current = current->next;
free( tmp );
}
free( *h );
*h = NULL;
}
int main() {
node n = newNode(1);
head h = newHead(n);
node n2 = newNode(2);
node n3 = newNode(3);
node n4 = newNode(4);
n->next = n2;
n2->next = n3;
n3->next = n4;
printf("%i", h->first->id);
printf("%i", h->first->next->id);
printf("%i", h->first->next->next->id);
printf("%i\n", h->first->next->next->next->id);
delete( &h );
return 0;
}
它的输出是
1234
1234
输出的第二行包含来自函数的测试消息delete
。
推荐阅读
- python - 将行值与列名进行比较并突出显示 Pandas 中的相交单元格
- javascript - 从 ffmpeg 到 html 的实时视频源,延迟最小
- erlang - 如何测试 msg 是否发送到 GenServer 进程
- reactjs - 更新到 Windows 2004 后,我的 LocalHost:3000 无法正常工作
- reactjs - 找不到 webpack 的 React 组件中使用的动态图像 src
- c++ - 可以将 lambdas 用作非类型模板参数吗?
- dialogflow-es - Dialogflow 实现答案未达到 Telegram、Facebook 和 Slack 集成
- vb.net - 如何跟踪媒体播放器播放列表上的文件名并获取当前播放文件索引
- c - c != '\n' 条件在“for”循环(C 语言)中的作用是什么?
- ios - 如何在 iPadOS 上捕获鼠标事件