c - 为什么带有双指针的链表会导致错误?
问题描述
我问你一个问题是因为我做的任务没有成功。该结构是一个普通的链表,在main中声明头指针,并将头指针的地址值作为参数传递给函数。全局变量 top 用于确定当前数据的位置。
当前下面的代码在执行时将仅检测错误。
结构:
struct ListNode{
int data;
struct ListNode* link;
};
int top = 0;
代码:
void DisplayList(ListNode** head){
if(*head == NULL){
printf("List = Empty\n");
}
else{
printf("List = ");
for(;(*head) != NULL; *head = (*head)->link){
printf("%d ",(*head)->data);
}
}
printf("\n");
}
void AddList(ListNode** head){
ListNode* temp = (ListNode*)malloc(sizeof(ListNode));
int num;
printf("Data register) ");
scanf("%d",&num);
temp->data = num;
temp->link = NULL;
top++;
if(*head == NULL){
*head = temp;
}
else{
for(;(*head)->link != NULL; *head = (*head)->link){}
(*head)->link = temp;
}
DisplayList(head);
}
预期结果:
数据寄存器)10 列表 = 10
数据寄存器) 20 列表 = 10 20
数据寄存器) 30 列表 = 10 20 30
解决方案
您不应该*head
在循环中进行修改。您需要使用局部变量来单步执行列表,否则您将更改调用者的变量以指向列表的末尾。
void DisplayList(ListNode** head){
if(*head == NULL){
printf("List = Empty\n");
}
else{
printf("List = ");
for(ListNode *step = *head;step != NULL; step = step->link){
printf("%d ",step->data);
}
}
printf("\n");
}
void AddList(ListNode** head){
ListNode* temp = (ListNode*)malloc(sizeof(ListNode));
int num;
printf("Data register) ");
scanf("%d",&num);
temp->data = num;
temp->link = NULL;
top++;
if(*head == NULL){
*head = temp;
}
else{
ListNode *step = *head;
for(;step->link != NULL; step = step->link){}
step->link = temp;
}
DisplayList(head);
}
推荐阅读
- javascript - 客户端速度测试
- c# - EF Core 有条件地启用延迟加载
- javascript - Google Docs - programmatically send mouse click to an item in outline pane
- spring - Find by object attribute spring data
- .net - 绕过 tumblr 条款页面
- azure - Azure - 未在您的订阅区域提供
- javascript - Labeling for Highcharts Funnel Visualization
- bash - Go Sha256Sum Difference with Bash sha256sum
- phpstan - PHPstan 规则从 7.0 迁移到 7.2
- tensorflow - 在 Tensorboard 中显示每个类别的指标