我已经嵌套了while循环,从文件中读取行并创建邻接列表 . 问题似乎不是内部循环,因为它通过那个,但它在将最后一个点从文件保存到邻接列表之前就停止运行 . 我已经测试了几个不同的文件(不同大小),它总是在最后一点之前 . 我不能为我的生活弄清楚为什么会这样做,但也许其他人可以帮助我?
文件中的行很好地存储在current-> next数组中,它只是我遇到麻烦的newPt邻接列表的最后一行 . 实际上,它是最后一次进入while循环,它似乎无法执行最后几行 .
while(fscanf(fptr, "%d %d %d", &u, &v, &w) != EOF) { //read from file
current->next=malloc(sizeof(struct line));
current=current->next;
current->u=u;
current->v=v;
current->w=w;
current->useful=0;
//add point to adjacency list
currentPt=aList[u];
while((currentPt->adj)!=NULL) {
currentPt=currentPt->adj;
}
newPt=malloc(sizeof(struct adjacent));
newPt->x=v;
newPt->adj=NULL;
currentPt->adj=newPt;
}
这些是我正在使用的结构,如果这有帮助:
struct line {
int u;
int v;
int w;
int useful;
struct line *next;
};
struct adjacent {
int x;
int onqueue;
struct adjacent *adj;
};
struct adjacent *aList[num+1];
struct line *current;
struct adjacent *currentPt;
3 回答
您需要更仔细地检查
fscanf
的返回值 . 如果它在文件末尾,它将返回EOF
. 但是你需要它返回3,表示3次成功转换 . 例如,如果您的文件以空行结束,它可能会返回0
.为了调试,您可以添加用于打印中间状态的行:
加
在外部while循环的末尾 .
你能尝试以下方法吗?
让我知道这个是否奏效 .