gpt4 book ai didi

c - 简单链表实现逻辑错误?

转载 作者:行者123 更新时间:2023-11-30 20:20:34 25 4
gpt4 key购买 nike

我已经实现了一个链表代码,但是我的代码中似乎存在逻辑错误,有人可以帮我解决这个问题吗?

struct Node{
int val;
struct Node *next;
};
void add(struct Node *new_node, struct Node *head){
struct Node *new_n;
if( head == NULL){
head = new_node;
}
else{
new_n = head;
while(new_n){
new_n = new_n->next;
}
new_n = new_node;
}
}
void print(struct Node*n){
while(n != NULL){
fprintf(stderr, "val:%d addr%p \t next%p\n",n->val, n, n->next);
n=n->next;
}
}

void main (){
struct Node *head;
struct Node *node;
int i ;
for( i =1; i< 5; i++){
struct Node *node = malloc(sizeof(*node));
bzero(node,sizeof(*node));
node->val = i;
node->next =NULL;
add(node, head);
}
print(head);
}

这段代码不打印任何值?这段代码有什么问题?[我使用:$gcc filename.c -o filename.o]

最佳答案

我发现三个问题:

1) head 从未初始化

用途:

struct Node *head = NULL;

2) 在 add 函数中对 head 的更改不会改变 main< 中的 head/

尝试

void add(struct Node *new_node, struct Node **head){
^^

并在函数中使用*head并像add(node, &head);

一样调用它

3) 新元素不会添加到列表中。

尝试:

void add(struct Node *new_node, struct Node **head) {
struct Node *new_n;
if (*head == NULL) {
*head = new_node;
}
else {
new_n = *head;
while (new_n->next) { // Notice - iterate until the next pointer is NULL
new_n = new_n->next;
}
new_n->next = new_node; // Notice
}
}

关于c - 简单链表实现逻辑错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45813943/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com