当我想将项目添加到链接列表时,我的程序崩溃了。 这是我正在使用的结构
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/