c - 如何将新节点添加到链表的开头?
问题描述
我正在尝试创建一个将节点添加到链表开头的函数。我已经创建了新节点并成功地将新节点指向了链表中的原始标题。但是,我不确定如何将我的新节点设置为链表的标题。
void insert_node(BURGER* header)
{
BURGER* tp1;
printf("Enter the details of record to be inserted in the format as\n");
printf("<name>\n<popularity>\n");
scanf_s("%s", &name, sizeof(name));
scanf("%d", &popular);
tp1 = make_node(name, popular);
tp1->next = header;
header = tp1;
//printf("%d", tp1->next->popularity);
printf("\n\n New record inserted at the start of the List\n");
}
亲切的问候
解决方案
我认为你的思考过程是正确的。但是,该代码不起作用,因为您尝试将新节点设置为标头,而这不起作用,因为BURGER * header
它是指向标头的指针的副本。所以你可以这样做:
void insert_node(BURGER** header)
{
BURGER* tp1;
printf("Enter the details of record to be inserted in the format as\n");
printf("<name>\n<popularity>\n");
scanf_s("%s", &name, sizeof(name));
scanf("%d", &popular);
tp1 = make_node(name, popular);
tp1->next = *header;
*header = tp1;
//printf("%d", tp1->next->popularity);
printf("\n\n New record inserted at the start of the List\n");
}
这样,您正在修改原始指针并更新链表的标题。
推荐阅读
- powershell - 未找到 VSCode、Powershell、cmdlet (Netlify) 'netlify init'
- c# - 在 Visual Studio 中编写的 Azure 队列触发函数未侦听队列
- ios - 取消粗体通知权限 UI 警报操作文本
- python - 如何逐渐将当前的 Django 单元测试转移到 pytest?
- r - 在 Linux 环境中我的本地目录上安装 R-3.6.0
- c++ - 如何避免直接链接到 cmake 中的库文件?
- scala - Scala Play readNullable 无法读取地图类型
- r - 如何将四列转换为两列
- c# - Windows 服务卸载
- ocaml - 如何将 Hashable 模块的密钥类型限制为与签名中的类型参数相同?