c - 在链表C中添加项目

标签 c list input linked-list

当我想将项目添加到链接列表时,我的程序崩溃了。 这是我正在使用的结构

typedef struct seats
    {
    int number, reserved;
    char name[1000]; 
    } seats;
    // node list
    typedef struct node
    {
    seats seat;
    struct node * next;
    } node_t;

这是我的插入函数

void AddSeat(node_t * head, seats a_seat) // unos podataka na kraj liste
    {
    node_t * current = head;
    while (current->next != NULL) {
        current = current->next;
    }

    /* now we can add a new variable */
    current->next = malloc(sizeof(node_t));
    current->next->seat = a_seat;
    current->next->next = NULL;
    }

最佳答案

其实我觉得你的逻辑是错误的。

在链表中,您从一个空节点开始:

[]->

当你有东西要存储时,你就填充节点。

[X]->

然后在其末尾创建一个新的空节点。

[X]->[]

等等..等等..

[X]->[X]->

[X]->[X]->[]

在您的代码中,您正在将值添加到新元素。当您位于列表的末尾时,您将席位分配给当前节点,然后在末尾创建一个新的(空)节点 。您还应该为节点创建一个变量,为其分配内存,然后将节点指向它。

为了让链接列表工作,你可以在哪里

/* now we can add a new variable */
current->next = malloc(sizeof(node_t));
current->next->seat = a_seat;
current->next->next = NULL;

你应该有

void AddSeat(node_t *head, seats a_seat){
    node_t *current = head;
    node_t *new_node;

    ...

    new_node = malloc(sizeof(node_t));
    current->seat = a_seat;
    current->next = new_node;

    ...

}

此外,在用 C 语言编写代码时,请考虑遵循一些良好做法,例如将指针运算符 (*) 附加到变量名称(char *var 而不是 char * var )并正确缩进你的代码。它大大提高了可读性。

关于c - 在链表C中添加项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37600289/

相关文章:

使用后量子公钥算法在 C 中创建 X509 证书?

python - 如何在 Delphi 中使用 C API 函数 PyArg_ParseTupleAndKeywords?

C fprintf/fscanf 优化大文件速度

java - 在java中对日期值进行排序

javascript - 以编程方式使 input[type=url] 的数据列表出现在 JavaScript 中

c - 是否可以通过分配内存来恢复 secret 数据(例如用于解密的空闲内存中的 RSA 私钥)?

list - Lisp 用于列表处理。有树处理的语言吗?

python - 在Python循环下访问迭代列表中的所有元素

javascript - jquery获取输入框的值

Javascript::图像预览