gpt4 book ai didi

无法创建单向链表

转载 作者:行者123 更新时间:2023-12-01 23:49:06 25 4
gpt4 key购买 nike

我在创建链表时遇到问题:我不知道代码哪里出错了,你能帮帮我吗?这是代码:

#include <stdio.h>
#include <stdlib.h>
#define LENGTH 255

struct node {
int info;
struct node *next;
} *head = NULL;

int create(FILE **data){
char read[LENGTH];
printf("Write data file name: ");
scanf("%s", read);
*data = fopen (read, "r");

if (data == NULL) {
printf("Error reading given file.");
}

return 0;
}

int put_Symbols_into_list(FILE *data) {

struct node *new_node, *current;
char c;

printf("Data given: ");
while (!feof(data)){
new_node = (struct node*)malloc(sizeof (struct node));
c = fscanf(data, "%s", &new_node -> info);
printf("%s ", &new_node -> info);

if (head == NULL){
head = new_node;
current = new_node;
} else {
current -> next = new_node;
current = new_node;
}
}

}


int main() {
FILE *data;
struct node *n;
create(&data);
put_Symbols_into_list(data);
//display_List(n);
return 0;
}

我做的步骤:读取字符串的数据文件并将其放入新节点;如果 HEAD 节点没有任何数据,则将读取的数据放入其中;否则将其放入新节点。如此循环,直到数据文件中没有数据为止。您可以创建新的数据文件并将数据放入其中,例如 1 0 1 1 2 3 4 5 6

最佳答案

添加新节点后,您没有将 current->next 设置为 NULL。当您尝试浏览一个列表时,这会产生问题,因为您不知道它在哪里结束。我希望这就是您面临的问题。

此外,您还有冗余代码,因为 current 在添加后将始终指向 new_node。所以你不必把它同时放在 if 和 else block 中。只是一个建议。

关于无法创建单向链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27492127/

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