这个方法的好处在于我可以不用知道我要导入的文件中有几个链表结点,只需要设定一个使循环输入结束的条件即可。同样也可以运用到手动输入建立初始单链表的模式当中。
#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(struct student)
struct student
{
long num;
float score;
struct student *next;
};
struct student* creat()
{
struct student *head;
head = (struct student*)malloc(sizeof(struct student));
struct student *p1 = NULL;
struct student* end = NULL;
head->next = NULL;
end = head;
p1=(struct student*)malloc(LEN);
scanf("%ld,%f", &p1->num, &p1->score);
while (p1->num != 0)
{
end->next = p1;
end = p1;
p1= (struct student*)malloc(LEN);
scanf("%ld,%f", &p1->num,&p1->score);
}
end->next = NULL;
return (head); //返回了一个头节点,这样print函数才可以使用他
}
void print(struct student *head)
{
struct student *p;
p = head->next;
while (p != NULL)
{
printf("%ld %f\n", p->num, p->score);
p = p->next;
}
}
int main()
{
struct student *L1;
L1=creat();
print(L1);
return 0;
}
同时还有第二种更为简洁明了的方法,不用返回头指针的方法
#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(struct student)
struct student
{
long num;
float score;
struct student *next;
};
void creat(struct student *head)
{
FILE *fp1;
fp1 = fopen("database.txt", "r");
//head = (struct student*)malloc(sizeof(struct student));//切记这行要注释掉,不然调用函数传递地址会传入到新分配的内存当中去,而不是传到*head这个头指针本身
struct student *p1 = NULL;
struct student* end = NULL;
head->next = NULL;
end = head;
p1 = (struct student*)malloc(LEN);
fscanf(fp1,"%ld,%f", &p1->num, &p1->score);
while (p1->num != 0)
{
end->next = p1;
end = p1;
p1 = (struct student*)malloc(LEN);
fscanf(fp1,"%ld,%f", &p1->num, &p1->score);
}
end->next = NULL;
}
void print(struct student *head)
{
struct student *p;
p = head->next;
while (p != NULL)
{
printf("%ld %f\n", p->num, p->score);
p = p->next;
}
}
int main()
{
struct student *L1;
L1 = (struct student*)malloc(LEN);
L1->next = NULL;
creat(L1);
print(L1);
return 0;
}