2024/3/28 IOday1

编写一条学生链表,写一些能够像链表里边添加数据的函数 实现:将链表中的所有内容保存到文件中去 以及 读取文件中的所有内容,加载到链表里

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef int datatype;
typedef struct node
{
	char name[10];
	int age;
	datatype class;
	struct node *next;
}node,*node_p;
node_p create_link()
{
	node_p p=(node_p)malloc(sizeof(node));
	if(p==NULL)
	{
		printf("ERROR\n");
		return NULL;
	}
	p->next=NULL;
	return p;
}
void create_node(node_p L,char name[10],int age,datatype class)
{
	node_p new=(node_p)malloc(sizeof(node));
	if(new==NULL)
	{
		printf("ERROR\n");
		return ;
	}
	new->next=L->next;
	L->next=new;
	strcpy(new->name,name);
	new->age=age;
	new->class=class;

}
void free_link(node_p L){
	node_p temp;
	while(L!=NULL){
		temp=L;
		L=L->next;
		free(temp);
	}
}
void show(node_p L)
{
	if(L==NULL)
	{
		printf("ERROR\n");
		return ;
    }
	node_p p=L->next;
	while(p!=NULL)
	{
		printf("%s %d %d\n",p->name,p->age,p->class);
		p=p->next;
	}
}
int main(int argc, const char *argv[])
{
	node_p L=create_link();
	create_node(L,"gg",18,9);
	create_node(L,"liu",17,7);
	create_node(L,"ff",18,11);
//	show(L);
	FILE* fp=fopen("./student.txt","w");
	node_p p=L->next;
	while(p!=NULL)
	{
		fprintf(fp,"%s %d %d\n",p->name,p->age,p->class);
		p=p->next;
	}
	fclose(fp);

	FILE* fp2=fopen("./student.txt","r");
	node_p H=create_link();
	char na[10];
	int ag=0;
	int cl=0;
	while(fscanf(fp2,"%s %d %d",na,&ag,&cl)==3){
		create_node(H,na,ag,cl);
	}
	show(H);
	free_link(L);
	free_link(H);
	fclose(fp2);
	return 0;
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值