gpt4 book ai didi

c - 用C语言构建链表

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

我有一个文件,其中每一行都包含数据。我需要复制链表每个元素中的每一行字符串,然后打印它。但列表没有打印出来,也许问题出在构建列表的元素上。

typedef struct node
{
char *name;
struct node *next;
}node;

node *head = NULL;

node* listall()
{
char temp[50] ;
FILE *f1 = fopen("user_data.txt", "rt");
if(f1 == NULL)
{
printf("file not found \n");
return 0;}
//allocate memory for node
node *ptr = malloc(sizeof(node));
//allocate memory to hold the name
ptr->name = malloc(1000);

while(fgets(temp,50,f1)!= NULL){
//copy the current name
strcpy(ptr->name,temp);
head = ptr->next;
head->next = NULL; }
return head;

}
void list_print(node *head) {
node *p;
for (p = head; p != NULL; p = p->next)
printf("%s", p->name);
printf("\n");
}

最佳答案

下面是一个示例,说明您的 listall() 函数如何在从文件中读取数据时创建一个列表,该列表基于您的代码并带有解释所发生情况的注释:

node* listall()
{
char temp[50];
FILE* f1 = fopen("user_data.txt", "rt");
if (f1 == NULL)
{
printf("file not found \n");
return NULL;
}
node* ptr = NULL; /// Until/unless we find something in the file, we have an empty list!
node* head = NULL; /// This will be our answer - the START of the list!
while (fgets(temp, 50, f1) != NULL) {
node* add = malloc(sizeof(node));
add->name = malloc(100);
add->next = NULL; /// This will be the 'new' last node!
strcpy(add->name, temp); //copy the current name
if (ptr != NULL) ptr->next = add; /// Append node to end (if list is not empty)
else head = add; /// This is the first entry, so copy address to our answer.
ptr = add; /// And keep track of our last (= just created) node.
}
fclose(f1); /// Don't forget to close the file when you'e finished with it!
return head;
}

如何执行此操作有很多变体,您会通过快速谷歌搜索发现。

关于c - 用C语言构建链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59088047/

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