通过建立单链表的方式从文件中读入信息

这个方法的好处在于我可以不用知道我要导入的文件中有几个链表结点,只需要设定一个使循环输入结束的条件即可。同样也可以运用到手动输入建立初始单链表的模式当中。

#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;
}

  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值