在c中实现链表时无法推送



下面是我的部分链表代码:

struct node {
float data;
int key;
struct node* next;
};
typedef struct{
struct node *head;
struct node *current;
int length;
} linked_list;
linked_list *init_list(){
linked_list *out = malloc(sizeof(linked_list));
struct node *head = NULL;
struct node *current = NULL;
out->head = head;
out->current = current;
out->length = 0;
return out;
}
void push_core(struct node *head, int key, float data){
struct node *link = malloc(sizeof(struct node));
link->data = data;
link->key = key;
link->next = head;
// readjust to point at the new first node
head = link;
printf("%f; ", head->data);
}
void push(linked_list *list, int key, float data){
push_core(list->head, key, data);
list->length ++;
}
void print_list_core(struct node *head){
struct node* ptr = head;
printf("n[");
while(ptr != NULL){
printf("(%d,%f)", ptr->key, ptr->data);
ptr = ptr->next;
}
}
void print_list(linked_list *list){
print_list_core(list->head);
}

但是在主,我初始化链表结构后,我不能使用push()来链接新的指针,为什么呢?

linked_list *S = init_list();
for (int i = 0; i < n; i++)
{
push(S,i,0);
print_list(S);
printf("%d;", S->length);
}

澄清一下,列表的长度更新是正确的。但是当我试图打印列表时,它不起作用。此外,有趣的是,在另一个文件中,当我最初只是使用节点结构并为head和current定义全局变量时,代码工作得很好。但是,当我试图将它们包装在这个linked_list结构体中时,事情并不像预期的那样工作。

问题发生是因为您将list->head的指针值作为参数传递给push_code函数。这是函数call-by-value。因此,当您更改push_core函数内部的head指针时,它实际上不会更改您期望的list->head指针。一种快速修复方法是从push_core函数返回新创建的link指针,并将其保存为list->head。下面的代码应该可以解决您的问题。

struct node * push_core(struct node *head, int key, float data){
struct node *link = malloc(sizeof(struct node));
link->data = data;
link->key = key;
link->next = head;

return link;
}
void push(linked_list *list, int key, float data){
list->head = push_core(list->head, key, data);
list->length ++;
}