【发布时间】:2021-08-23 17:17:40
【问题描述】:
我目前正在学习 C 中的链表,并尝试编写一个函数以在末尾插入一个节点,然后打印所有数据。
一开始我的功能不起作用(只打印了1 2)
struct node {
int data;
struct node *link;
};
void add_end(struct node *head, int a){
struct node *current, *temp;
current = head;
temp = (struct node*)malloc(sizeof(struct node));
temp->data = a;
temp->link = NULL;
while(current != NULL){
current = current->link;
}
current = temp;
};
int main()
{
struct node *head;
head = (struct node *)malloc(sizeof(struct node));
head->data = 1;
head->link = NULL;
struct node *current;
current = (struct node *)malloc(sizeof(struct node));
current->data = 2;
current->link = NULL;
head->link = current;
add_end(head, 3);
current = head;
while(current != NULL){
printf("%d\n", current-> data);
current = current->link;
}
return 0;
}
修复一段时间后它工作了(打印了 1 2 3)
void add_end(struct node *head, int a){
struct node *current, *temp;
current = head;
temp = (struct node*)malloc(sizeof(struct node));
temp->data = a;
temp->link = NULL;
while(current->link != NULL){
current = current->link;
}
current->link = temp;
};
谁能告诉我为什么第一个不起作用。我认为它们是相同的,因为在第一个版本中:current 是最后一个节点的链接,它是下一个节点(null)的地址,而在第二个版本中:current->link 是最后一个节点的链接,它也是下一个节点的地址(null)。
【问题讨论】:
-
第一个不起作用,因为最终分配给
current绝对不会改变列表本身;它所做的只是改变局部变量current指向的内容。之后,函数存在,分配的内存泄漏。第二个仅在head引用函数初始节点时才有效。没有那个,它也不起作用(实际上会调用未定义的行为)。
标签: c linked-list