gpt4 book ai didi

c - 通过文本文件读入并显示链表

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

我正在尝试读取链接列表中的文本文件并成功显示它。但是我不断收到与 (head==NULL) 相对应的“列表为空”消息,同时我可以通过使用读取函数中的 put(id->...) 参数成功读取并打印文件一次但我无法使用上面提到的显示功能。

    struct node
{
char name[50];
int id;
struct node *next;
} *head;

int main()
{
int i,num;
struct node *r;
head=NULL;
readfile(*r);
while (1)
{
printf("\nList Operations\n");
printf("============\n");
printf("1.Insert\n");
printf("2.Display\n");
printf("3.Delete by ID\n");
printf("4.Delete by Name\n");
printf("5.Exit\n");
printf("Enter your choice: ");

if (scanf("%d", &i) <= 0){
printf("Enter only an integer\n");
exit(0);
} else {
switch(i)
{
case 1:
if(head==NULL)
{
printf("List is Empty\n");
}
else
{
printf("Element in the list are: ");
}
display(r);
break;
case 2:
return 0;
default:
printf("Invalid Choice\n");
}
}
}

void readfile(struct node *r)
{
r=head;

char str[50];
int id;
FILE *ifp=fopen("One.txt","r");
while (fgets(str,50,ifp)!=NULL){
r =(struct node *)malloc(sizeof(struct node));
char *token=strtok(str,",");
strcpy(r->name,token);
puts(r->name);
token=strtok(NULL,"\n");
r->id=token;
puts(r->id);
r->next=NULL;
r=r->next;
}
}

void display(struct node *r)
{
r = head;
if(r == NULL)
{
return;
}
while(r != NULL)
{
printf("Student %s has id %d.\n", r->name,r->id);
r = r->next;

}
printf("\n");
}

最佳答案

在您提供的代码中,您永远不会向 head 分配或分配任何内容。我想你需要在下面的某个地方添加代码

if (head == NULL) {
head = r;
}

if (head == NULL) {
head = (struct node *)malloc(sizeof(struct node));
// and initialize it with something
}

此外,我建议您创建更通用的函数,例如 add_node,如下所示

void add_node( struct node *r ) {
if(head == NULL) {
head = r;
} else {
struct node* n = head;
while(n->next != NULL) { // go to the end of the list
}
r->next = NULL; // to be sure this will be end of list
n->next = r;
}
}

然后在readfile中读取数据,创建新节点并将其传递给add_node

关于c - 通过文本文件读入并显示链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28400430/

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