在c中的链表末尾添加一个新节点



我试图在C中添加一个新节点到链表的末尾,但是我的代码有问题。这是我试过的

#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *head = NULL;
void add_node(int data) {
struct node *new_node = malloc(sizeof(struct node));
new_node->data = data;
new_node->next = NULL;
if (head == NULL) {
head = new_node;
} else {
struct node *current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = new_node;
}
int *x = NULL;
*x = 5;
}
int main() {
add_node(5);
return 0;
}

然而,当我尝试运行这段代码时,我得到一个分段错误。谁能告诉我出了什么问题吗?我试过通过添加print语句来调试代码,但我不确定问题发生在哪里。我还试着反复检查我是否正确地使用malloc为新节点分配了内存。

在您更新的代码中,您将先前设置为NULL的指针x更改为NULL。消除垃圾代码,或者如果必须的话,让x指向一个整数:

int *x = &(int) {0};
*x = 5;

我建议您删除全局变量如下:

#include <stdlib.h>
struct node {
int data;
struct node *next;
};
void add_node(struct node **head, int data) {
struct node *new_node = malloc(sizeof(struct node));
if(!new_node) {
// handle error
return;
}
new_node->data = data;
new_node->next = NULL;
if (!*head) {
*head = new_node;
return;
}
struct node *current = *head;
for(;current->next; current = current->next);
current->next = new_node;
}
int main() {
struct node *head = NULL;
add_node(&head, 5);
}

最新更新