student.c用链表完成
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct student
{char name[10];int chinese;int math;int English;int physics;int chemistry;int biology;
}stu,*stuptr;
typedef struct node
{union{stu data;int len;};struct node* next;
}node,*nodeptr;
nodeptr creat_head()
{nodeptr h = (nodeptr)malloc(sizeof(node));if(NULL == h){printf("创建失败\n");return NULL;}h->len = 0;h->next = NULL;return h;
}
nodeptr node_creat(char a[10],int num1,int num2,int num3,int num4,int num5,int num6)
{nodeptr p = (nodeptr)malloc(sizeof(node));if(NULL==p){printf("创建失败\n");return NULL;}strcpy(p->data.name,a);p->data.chinese=num1;p->data.math=num2;p->data.English=num3;p->data.physics=num4;p->data.chemistry=num5;p->data.biology=num6;p->next=NULL;return p;
}
int node_add(nodeptr h,char a[10],int num1,int num2,int num3,int num4,int num5,int num6)
{if(NULL==h){printf("插入失败\n");return 0;}nodeptr p=node_creat(a,num1,num2,num3,num4,num5,num6);p->next=h->next;h->next=p;h->len++;return 1;
}
int show(nodeptr h)
{if(NULL==h){printf("遍历失败\n");return 0;}nodeptr p=h;while(p->next!=NULL){p=p->next;printf("姓名:%s\n",p->data.name);printf("语文:%d\n",p->data.chinese);printf("数学:%d\n",p->data.math);printf("英语:%d\n",p->data.English);printf("物理:%d\n",p->data.physics);printf("化学:%d\n",p->data.chemistry);printf("生物:%d\n",p->data.biology);printf("------------------------\n");}
}
int save(nodeptr h)
{if(NULL==h){printf("失败\n");return 0;}FILE* fp = fopen("student.text","w");nodeptr p=h;for(int i=0;i<3;i++){p=p->next;fprintf(fp,"%s %d %d %d %d %d %d\n",p->data.name,p->data.chinese,p->data.math,p->data.English,p->data.physics,p->data.chemistry,p->data.biology);}fclose(fp);return 1;
}
int load(stuptr p)
{FILE* fp = fopen("student.text","r");for(int i=0;i<3;i++){fscanf(fp,"%s %d %d %d %d %d %d\n",p[i].name,&p[i].chinese,&p[i].math,&p[i].English,&p[i].physics,&p[i].chemistry,&p[i].biology);}fclose(fp);return 1;
}
int Show(stuptr arr)
{for(int i=0;i<3;i++){printf("姓名:%s \n",arr[i].name);printf("语文:%d \n",arr[i].chinese);printf("数学:%d \n",arr[i].math);printf("英语:%d \n",arr[i].English);printf("物理:%d \n",arr[i].physics);printf("化学:%d \n",arr[i].chemistry);printf("生物:%d \n",arr[i].biology);printf("---------------------\n");}return 0;
}int main(int argc, const char *argv[])
{nodeptr h=creat_head();node_add(h,"chen",99,88,99,88,98,88);node_add(h,"yu",99,98,99,78,98,88);node_add(h,"lin",99,88,99,98,98,98);save(h);stu arr[3];load(arr);show(h);Show(arr);return 0;
}
运行结果