学习记录
#include<stdio.h>
#include<stdlib.h>
struct student
{
int id;
int score;
struct student *next;
};
typedef struct student stu;
stu *cl(stu *head)//创
{
head=(stu*)malloc(sizeof(stu));
if(head==NULL)
{
printf("内存分配失败!\n");
exit(0);
}
head->next=NULL;
return head;
}
stu *al(stu *head,int id,int score)//加
{
stu *p,*pr=head;
p=(stu*)malloc(sizeof(stu));
if(p==NULL)
{
printf("内存分配失败!\n");
exit(0);
}
p->id=id;
p->score=score;
while(pr->next!=NULL)
pr=pr->next;
pr->next=p;//切勿写反
p->next=NULL;//不写就会报错
return head;
}
stu *il(stu *head,int pos,int id,int score)//插
{
stu *p,*pr=head;
p=(stu*)malloc(sizeof(stu));
if(p==NULL)
{
printf("内存分配失败!\n");
exit(0);
}
p->id=id;
p->score=score;
p->next=NULL;
if(pos==-1)
{
p->next=head->next;
head->next=p;
}
else
{
while(pr->id!=pos&&pr->next!=NULL)
{
pr=pr->next;
}
if(pr->id==pos)
{
p->next=pr->next;
pr->next=p;
}
}
return head;
}
stu *dl(stu *head,int id)//删
{
stu *p,*pre;
p=head->next;
pre=head;
while(p->id!=id&&p->next!=NULL)
{
pre=pre->next;
p=p->next;
}
if(p->id==id)
{
pre->next=p->next;
free(p);
}
return head;
}
int fl(stu *head,int id)//查
{
int score;
stu *p=head;
while(p->id!=id&&p->next!=NULL)
{
p=p->next;
}
if(p->id==id)
{
score=p->score;
return score;
}
return -1;
}
void disp(stu *head)//遍历
{
stu *p=head->next;
printf("当前所有学生信息如下:\n");
while(p!=NULL)
{
printf("学号:%-3d成绩:%-3d\n",p->id,p->score);
p=p->next;
}
}
int main()
{
int id;
int score;
int pos;
char c;
stu *head=NULL;
head=cl(head);
printf("请输入学生学号和成绩:\n");
scanf("%d%d",&id,&score);
head=al(head,id,score);
printf("创建成功,请输入\"Y\"继续创建,输入其他字符进入下一步。\n");
getchar();
c=getchar();
while(c=='Y')
{
printf("请输入学生学号和成绩:\n");
scanf("%d%d",&id,&score);
head=al(head,id,score);
printf("创建成功,请输入\"Y\"继续创建,输入其他字符进入下一步。\n");
getchar();
c=getchar();
}
printf("请输入插入学生的学号和成绩:\n");
scanf("%d%d",&id,&score);
printf("请输入要将该学生插入到哪位学生之后(输入其学号,-1代表插入到最前面):\n");
scanf("%d",&pos);
head=il(head,pos,id,score);
printf("插入成功。\n");
disp(head);
printf("请输入要删除学生的学号:\n");
scanf("%d",&id);
printf("被删除的学生的成绩为:%d\n",fl(head,id));
head=dl(head,id);
disp(head);
return 0;
}