编写一条学生链表,写一些能够像链表里边添加数据的函数
实现:将链表中的所有内容保存到文件中去以及读取文件中的所有内容,加载到链表里面
主函数
int main(int argc, const char *argv[])
{
node_p H=create_head();
//选择读取或者写入模式
printf(" r or w :");
char mode;
scanf("%c",&mode);
//以追加的方式打开文件
FILE *fp=fopen("./stu.txt","a+");
if(NULL==fp){
perror("open error");
return -1;
}
if('w'==mode){
Stu stu[3]={"zhangsan",20,"male",\
"lisi",21,"male",\
"wangwu",22,"female"};
insert_head(H,stu[0]);
insert_head(H,stu[1]);
insert_head(H,stu[2]);
node_p p=H->next;
while(p!=NULL){
fprintf(fp,"%s\n%d\n%s\n",p->data.name,p->data.age,p->data.sex);
p=p->next;
}
}
else if('r'==mode){
while(1){
node_p p=create_node();
int res=fscanf(fp,"%s%d%s",p->data.name,&(p->data.age),p->data.sex);
if(res<=0){
free(p);
break;
}
p->next=H->next;
H->next=p;
H->len++;
}
show_link(H);
}
fclose(fp);
return 0;
}
结构体类型
//学生结构体
typedef struct stu
{
char name[20];
int age;
char sex[10];
}Stu,*Stu_p;
//链表结构体
typedef struct node
{
union{
Stu data;
int len;
};
struct node *next;
}node,*node_p;
链表的函数
node_p create_head(){
node_p H=(node_p)malloc(sizeof(node));
if(NULL==H){
printf("创建失败\n");
return NULL;
}
H->next=NULL;
H->len=0;
return H;
}
node_p create_node(){
node_p new=(node_p)malloc(sizeof(node));
if(NULL==new){
printf("创建失败\n");
return NULL;
}
new->next=NULL;
return new;
}
//头插
int insert_head(node_p H,Stu data){
if(NULL==H){
printf("传入参数错误\n");
return -1;
}
node_p new=create_node();
if(NULL==new){
printf("创建失败\n");
return -1;
}
new->data = data;
new->next=H->next;
H->next=new;
H->len++;
return 0;
}
//遍历链表
void show_link(node_p H){
if(NULL==H||H->len==0){
printf("传参错误\n");
return;
}
node_p p=H->next;
while(p!=NULL){
printf("%s\n%d\n%s\n",p->data.name,p->data.age,p->data.sex);
p=p->next;
}
}
运行结果