【发布时间】:2020-03-19 22:33:02
【问题描述】:
我没有收到任何错误;该代码有效,但仅显示第一个元素,不显示其他元素。我想用链表显示文件中的所有数字。我的错误是什么?
numbers.txt中的数字:
9 2 3
4 2 3
1 2 9
2 4 8
7 5 9
2 4 7
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
struct NUMBERS{
int katsayi;
int taban;
int us;
NUMBERS *next;
};
int main(){
NUMBERS *temp=NULL;
NUMBERS *list=NULL; // to keep first element
NUMBERS *head=NULL; // temp for the first element
FILE *fp=fopen("numbers.txt","r+");
while(!feof(fp)){
temp=(NUMBERS*)malloc(sizeof(NUMBERS));
fscanf(fp,"%d %d %d",&temp->katsayi,&temp->taban,&temp->us);
temp->next=NULL;
if(list==NULL){
list=temp;
}
else{
head=list;
while(head->next!=NULL){
head=head->next;
}
head=temp;
}
}
head=list;
while(head!=NULL){
printf("%d %d %d",head->katsayi,head->taban,head->us);
head=head->next;
}
return 0;
}
【问题讨论】:
-
在
else部分的末尾,您使用head=temp。那么在这之前发生的所有head=...分配的意义何在???您不妨摆脱所有这些(包括while循环),并留下head=temp。我希望这会导致您遇到问题,因为您显然不打算只做head=temp。 -
是的,我的错:/,谢谢你的回答
标签: c file linked-list singly-linked-list