我有一个简单的任务,教授要求我们从文本文件中提取一些数字并加载到链表中。 我不想深入细节,但我有一个基本问题。
他给我们提供了一个如下的函数:
INTLIST* init_intlist( int n )
{
INTLIST *lst;
lst = (INTLIST *)malloc(sizeof(INTLIST));
lst->datum = n;
lst->next = NULL;
return lst;
}
这个函数用来初始化链表的第一个元素。然后他要求我们根据这个签名定义一个函数:
int insert_intlist( INTLIST *lst, int n )
所以我认为他只是希望我们将此添加到链表中,因此我尝试了这个:
int insert_intlist( INTLIST *lst, int n )
{
INTLIST* lstTemp;
lstTemp = (INTLIST *)malloc(sizeof(INTLIST));
lstTemp->datum = n;
lstTemp->next = lst;
lst = lstTemp;
free(lstTemp);
}
我的思路是创建一个临时节点,将数据值(Datum)赋值并将下一个指针指向当前指针指向的位置。然后我重新分配主指针到这个新创建的临时节点。
这样我们就有了例如两个节点:
[新的临时节点] -> [之前初始化的节点]
当我跟踪代码时,看起来很棒...
然后在主函数中我只需要编写一个打印列表的函数:
while (lst!=NULL)
{
printf("The value is:%d", lst->datum);
lst=lst->next;
}
问题在于这似乎只打印了一个数字(即我从文件中读取的第一个数字,我认为它是列表中的最后一个数字,或者至少我以为它是列表中的最后一个数字)。
但是它应该继续进行,因为我在文件中有10个数字。 我知道代码非常混乱,我会整理它……以下是我的整个主函数,如果有人需要更多信息:
#include <stdio.h>
#include <stdlib.h>
#include "intlist.h"
int main(int argc, char *argv[])
{
char c; /* Character read from the file. */
FILE* ptr; /* Pointer to the file. FILE is a
structure defined in <stdio.h> */
int index=0;
//INTLIST* aList[10]; //will use later
/* Open the file - no error checking done */
ptr = fopen("1.txt","r");
/* Read one character at a time, checking
for the End of File. EOF is defined
in <stdio.h> as -1 */
if(ptr==NULL) {
printf("Error: can't open file.\n");
/* fclose(file); DON'T PASS A NULL POINTER TO fclose !! */
return 1;
}
//aList[index] = malloc(sizeof(INTLIST)); WE NEED THIS LATER ON....
INTLIST *lst=NULL;
while ((c = fgetc(ptr)) != EOF)
{
if (c != ' ')
{
//make sure it isnt a space
int i = c - '0'; //get the value from the text file
if(c=='\n')
{
// aList[index]=lst;
// index++;
// aList[index] = malloc(sizeof(INTLIST));
while (lst!=NULL)
{
printf("The value is:%d", lst->datum);
lst=lst->next;
}
free(lst);
free(aList[index]);
return 0;
//new line in the file
//create another linked list
}
if (lst==NULL)
lst = init_intlist(i);
else
insert_intlist( lst, i);
}
}
fclose(ptr);
system("PAUSE");
return 0;
}
以下是 intlist.h 文件,供需要的人使用:
#ifndef __intlist_h__
#define __intlist_h__
/* each entry in the list contains an int */
typedef struct intlist {
int datum;
struct intlist *next;
} INTLIST;
INTLIST *init_intlist( int n ); /* initializes the intlist with initial datum n */
int insert_intlist( INTLIST *lst, int n ); /* Inserts an int (n) into an intlist from the beginning*/
void list_append(INTLIST *list, void *datum); /* Inserts entry to the end of the list */
INTLIST* list_front(INTLIST *list); /*return the element at the front of the list, and remove it
from the list*/
void list_map( INTLIST *list, void (*f)(void *) ); /*Applies a function to each element of the list */
void list_delete( INTLIST *list ); /* Deletes (and frees) all entries in the list */
#endif
int insert_intlist( INTLIST *lst, int n );
并且注释说将一个整数(n)从开头插入到intlist中,这是错误的:根据原型,这是不可能实现的。请查看我的答案以获取详细信息。 - Alok Singhal