#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct student
{
int id;
char name[20];
int score1,score2,score3;
} STUDEN;
typedef struct snode
{
STUDEN st;
struct snode *next;
} SNODE;
int input(SNODE *s)
{
printf("输入学号:\n");
scanf("%d", &s->st.id);
if (s->st.id == 0)
return 0;
printf("输入姓名和三门课程的成绩:\n");
scanf("%s%d%d%d", s->st.name, &s->st.score1, &s->st.score2, &s->st.score3);
while (getchar() != '\n') NULL;
s->next = NULL;
printf("\n");
return 1;
}
SNODE *create()
{
SNODE *head, *r, *s, sn;
if (!input(&sn))
return NULL;
head = (SNODE *)malloc(sizeof(SNODE));
r = head;
*r = sn;
while (input(&sn))
{
s = (SNODE *)malloc(sizeof(SNODE));
*s = sn;
r->next = s;
r = s;
}
return head;
}
void print(SNODE *p)
{
if (p==NULL)
{
printf("LinkList is NULL!\n");
return;
}
printf("StudentInformation:\n");
for (; p; p=p->next)
printf("%d %s %d %d %d\n", p->st.id, p->st.name, p->st.score1, p->st.score2, p->st.score3);
}
SNODE *insert(SNODE *head, SNODE *sn)
{
SNODE *p, *q, *s;
p = head;
q = NULL;
s = (SNODE *)malloc(sizeof(SNODE));
*s = *sn;
while (p)
{
if (p->st.id >= s->st.id)
{
s->next = p;
break;
}
q = p;
p = p->next;
}
if (q)
q->next = s;
else
head = s;
return head;
}
void _free(SNODE *p)
{
SNODE *q;
while (p)
{
q = p->next;
free(p);
p = q;
}
}
SNODE *_read(char *path)
{
FILE *fp = fopen(path, "rb");
SNODE sn, *head=NULL, *p, *q;
if (fread(&sn, sizeof(STUDEN), 1, fp) == 1)
{
head = (SNODE *)malloc(sizeof(SNODE));
q = head;
*q = sn;
q->next = NULL;
}
while (fread(&sn, sizeof(STUDEN), 1, fp) == 1)
{
p = (SNODE *)malloc(sizeof(SNODE));
*p = sn;
p->next = NULL;
q->next = p;
q = p;
}
fclose(fp);
return head;
}
void _save(SNODE *h, char *path)
{
FILE *fp = fopen(path, "wb");
while (h)
{
fwrite(h, sizeof(STUDEN), 1, fp);
h = h->next;
}
fclose(fp);
}
int main()
{
SNODE sn, *head = create();
_save(head, "stud.dat");
_free(head);
printf("\n输入插入的数据:\n");
if (input(&sn))
{
head = _read("stud.dat");
head = insert(head, &sn);
_save(head, "stud1.dat");
_free(head);
head = _read("stud1.dat");
print(head);
_free(head);
}
return 0;
}