我正在尝试创建一个包含其姓名和出生日期信息的人员链接列表。人员信息在结构中声明,当我创建newNode时,该newNode稍后会添加到列表的末尾。发生的事情是,我在insertNode函数中得到了一个无限循环,因为我的createNode函数在某种程度上改变了我的列表的头部。有时候我有所作为,有时却没有,这让我相信我做的一些小错误,我只是没有抓住。
我发布了以下代码。还有更多的主要内容,但我没有发布它,因为它一直很好。直到那时。
typedef struct info
{
char *firstName;
char *lastName;
int month;
int day;
int year;
struct info *next;
} person;
person *createNode(char *fName, char *lName, char *m, int d, int y)
{
person *n = malloc(sizeof(person));
n->firstName = strdup(fName);
n->lastName = strdup(lName);
n->month = convertMonthCharToInt(m);
n->day = d;
n->year = y;
n->next = NULL;
return n;
}
person *insertNode(person *head, person *newNode)
{
person *temp = NULL;
temp = head;
if(head == NULL)
return newNode;
for(temp = head; temp->next!=NULL; temp = temp->next);
if(head->next == NULL)
head->next = newNode;
return head;
}
int main()
{
int numClasses = 0, numStudents = 0, numQueries = 0, d = 0, y = 0, j = 0;
char fName[31], lName[31], m[11], queryFirstName[31], queryLastName[31];
person *print;
FILE *readFile = fopen("birthday2.txt", "r");
if(readFile == NULL)
{
printf("File does not exist. Closing program.\n");
return 0;
}
fscanf(readFile, "%d", &numClasses);
while(i<numClasses)
{
person *head = malloc(sizeof(person));
person *newNode = malloc(sizeof(person));
person *result = malloc(sizeof(person));
head = NULL;
fscanf(readFile, "%d", &numStudents);
j = 0;
while(j<numStudents)
{
//read names in from file
fscanf(readFile, "%s", &fName);
fscanf(readFile, "%s", &lName);
fscanf(readFile, "%s", &m);
fscanf(readFile, "%d", &d);
fscanf(readFile, "%d", &y);
fscanf(readFile, "%d", &numQueries);
//creates a node. My list head changes from here
newNode = createNode(fName, lName, m, d, y);
//to here. So I'm pretty sure it's changing within this function. Just not sure why.
head = insertNode(head, newNode);
}