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

在C中实现链表时无法推送,c,data-structures,linked-list,C,Data Structures,Linked List,以下是我链接列表的部分代码: 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(linke

以下是我链接列表的部分代码:

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);
}
linked_list*S=init_list();
对于(int i=0;ilength);
}

为了澄清,列表的长度确实正确更新。但是当我试图打印列表时,它不起作用。另外,有趣的是,在另一个文件中,当我最初使用node结构并为head和current定义全局变量时,代码运行良好。但是当我试图将它们封装在这个链表结构中时,事情并没有像预期的那样正常工作。

出现问题的原因是您将
list->head
的指针值作为参数传递给了
push\u code
函数。这是一个函数
按值调用
。因此,当您在
push_core
函数中更改
head
指针时,实际上不会更改您期望的
list->head
指针。一个快速修复方法是从
push_core
函数返回新创建的
链接
指针,并将其保存为
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 ++;
}

C语言按值传递函数参数。因此,在
push_core
中更新
head
不会对
列表
结构中的
head
指针产生任何影响。@user3386109我以为我传递了一个指针,所以它应该在上面写?那么我应该如何编辑代码以使其正常工作呢?我应该把它改成双指针吗?谢谢你能调试你的代码吗?如果我在写代码,我会去掉
push\u-core
print\u-list\u-core
函数,只需实现
push
print\u-list
。我并不想粗鲁,但有很多问题你应该用调试器来研究