gpt4 book ai didi

在 C 中创建一个链接列表,但是我创建的函数的结束条件是什么,因为它没有退出

转载 作者:太空宇宙 更新时间:2023-11-04 01:22:10 25 4
gpt4 key购买 nike

我是数据结构的新手,只是不知道链表的工作原理,所以我自己创建了一个链表,它与书中的不同,但无法理解我的代码中的问题在哪里,因为它不是退出。需要纠正的地方这是我的代码

struct node{
int data;
struct node* next;
};
void addAtBegining(int data,struct node* head){
struct node* new_node = (struct node*)malloc(sizeof(struct node));
new_node->data = data;
new_node->next = head->next;
head->next = new_node;
}
void display(struct node* head){
while(head->next!=NULL){
head = head->next;
printf("%d ",head->data);
}
}
void main(){
struct node* list = NULL;
addAtBegining(2,list);
addAtBegining(3,list);
addAtBegining(4,list);
addAtBegining(5,list);
addAtBegining(6,list);
display(list);
}

最佳答案

未定义的行为:您有 struct node* list = NULL 但随后您将 list 传递给 addAtBegining,这是在参数 head 然后执行 head->next

要么

  • 初始化head
  • 在addAtBegining中添加代码返回头指针,如果为空则分配
  • 添加双指针更新head

例如您可以执行以下操作

struct node* list = (struct node *) malloc (sizeof (struct node));
list->data = 0xdeafbabe;
list->next = NULL;

然后使用您现有的代码。

这样做只是用垃圾数据添加一个虚拟头节点。因为您的打印例程无论如何都会跳过头节点。这会很好用。

关于在 C 中创建一个链接列表,但是我创建的函数的结束条件是什么,因为它没有退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39695903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com