#include struct STU
{
int num;
char name[5];
int score;
struct STU *next;
};
struct STU *Creatlink_t();//创建链表
void Typelink_t(struct STU * phead);//打印里面的内容
struct STU *Charulink_t(struct STU * phead);//在里面插入新的内容
struct STU *detelelink_t(struct STU * phead);//删除里面的内容
void Chocklink_t(struct STU * phead);//搜索想要打印的节点
int choice();
int main()
{
struct STU *phead;
phead=Creatlink_t();
while(1)
{
switch(choice())
{
case 1:Typelink_t(phead);break;
case 2:Chocklink_t(phead);break;
case 3:Charulink_t(phead);break;
case 4:detelelink_t(phead);break;
case 0:exit(0);
}
}
}
int choice() /*菜单*/
{
int n;
printf(" 菜单 \n\n");
printf(" 1 打印链表里面的内容\n");
printf(" 2 查找链表里面的内容\n");
printf(" 3 在链表中插入一条信息\n");
printf(" 4 删除链表中的一个人信息\n");
printf(" 0 退出\n");
printf("----------------------------end----------------------\n\n");
printf(" 请输入(0-4) ");
scanf("%d",&n);
return n;
}
struct STU *Creatlink_t()
{
int i,n;
FILE *fp;
struct STU *phead;
struct STU *p;
struct STU *pt;
fp=fopen("a.txt","r+b");
printf("输入n个学生的信息");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
p=(struct STU *)malloc(sizeof(struct STU));
printf("输入第%d个学生的信息:学号,姓名,分数\n",i);
scanf("%d %s %d",&p->num,p->name,&p->score);
fprintf(fp,"%d %s %d",p->num,p->name,p->score);
if(i==1)
{
phead=p;
pt=p;
}
else
{
pt->next=p;
pt=p;
}
}
p->next=NULL;
fclose(fp);
return phead;
}
void Chocklink_t(struct STU * phead)
{
FILE *fp;
fp=fopen("a.txt","r+b");
if(phead==NULL)
{
printf("链表为空\n");
return ;
}
struct STU *p;
int n;
int i;
printf("请输入要查找的学号\n");
scanf("%d",&n);
p=phead;
while((p->num!=n)&&(p->next!=NULL))
{
p=p->next;
}
if(n==p->num)
{
printf("%d %s %d\n",p->num,p->name,p->score);
fprintf(fp,"%d %s %d\n",p->num,p->name,p->score);
}
else
printf("查无此人\n");
fclose(fp);
}
void Typelink_t(struct STU * phead)
{
FILE *fp;
fp=fopen("a.txt","r+b");
struct STU *p;
if(phead==NULL)
{
printf("该链表为空");
}
else
p=phead;
while(p!=NULL)
{
printf("%d %s %d\n",p->num,p->name,p->score);
fprintf(fp,"%d %s %d\n",p->num,p->name,p->score);
p=p->next;
}
fclose(fp);
}
struct STU *Charulink_t(struct STU * phead)
{
struct STU *pf,*pt;
struct STU * p=(struct STU *)malloc(sizeof(struct STU ));
printf("请输入要插入的学号 姓名 成绩:");
scanf("%d %s %d",&p->num,p->name,&p->score);
if(phead==NULL) //当链表是空链表的时候
{
phead=p;
p->next=NULL;
return phead;
}
pf=phead;
while(p->num >pf->num && pf->next!=NULL)
{
pt=pf;
pf=pf->next;
}
if(p->num < pf->num)
{
if(pf==phead)
{
p->next=phead;
phead=p;
}
else
{
pt->next=p;
p->next=pf;
}
}
else
{
pf->next=p;
p->next=NULL;
}
//return phead;
}
struct STU *detelelink_t(struct STU * phead)
{
int n;
struct STU *p;
struct STU *pt;
printf("请输入要删除的节点");
scanf("%d",&n);
if(phead==NULL)
{
printf("该链表为空\n");
return ;
}
else
p=phead;
while(p->num!=n&&p->next!=NULL)
{
pt=p;
p=p->next;
}
if(p->num==n)
{
if(p==phead)
{
phead=p->next;
}
else
pt->next=p->next;
free(p);
}
else
printf("该链表没有此节点");
//Typelink_t(phead);
}