【问题标题】:Not able to push when implementing linked list in C在 C 中实现链表时无法推送
【发布时间】:2021-05-20 22:34:22
【问题描述】:

这是我的链表代码的一部分:

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 结构中时,事情并没有按预期工作。

【问题讨论】:

  • C 语言按值传递函数参数。所以更新push_core 中的head 不会对list 结构中的head 指针做任何事情。
  • @user3386109 我以为我传递了一个指针,所以它应该写在上面?那么我应该如何编辑代码以使其工作?我应该将其更改为双指针吗?谢谢!
  • 你能调试你的代码吗?
  • 如果我在写代码,我会去掉push_coreprint_list_core函数,只实现pushprint_list
  • 我并不是要粗鲁,但是您应该使用调试器研究很多问题

标签: c data-structures linked-list


【解决方案1】:

出现问题是因为您将list-&gt;head 的指针值作为参数传递给了push_code 函数。这是一个函数call-by-value。因此,当您更改 push_core 函数内的 head 指针时,它实际上不会更改您期望的 list-&gt;head 指针。一种快速解决方法是从push_core 函数返回新创建的link 指针并将其保存为list-&gt;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 ++;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    相关资源
    最近更新 更多