#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(struct student)
/*
顺序链表的创建、删除、插入操作
*/
struct student{
int num;
float score;
struct student *next;
};
int n;
struct student *creat(){//创建链表;
struct student *head;//头结点
struct student *p1,*p2;
p1=p2=(struct student *)malloc(LEN);//分配内存
printf("\n请输入学号\n");
scanf("%d",&p1->num);
printf("\n请输入分数\n");
scanf("%f",&p1->score);
head=NULL;
n=0;
while(p1->num){
n++;
if(n==1){
head=p1;
}else{
p2->next=p1;
}
p2=p1;
p1=(struct student *)malloc(LEN);
printf("\n请输入学号");
scanf("%d",&p1->num);//输入为0则条件为0停止循环
printf("\n请输入分数");
scanf("%f",&p1->score);
}
p2->next=NULL;
return head;
}
void print(struct student *head){//输出链表
struct student *p;//定义指针
p=head;//指针传递
if(head){
do{
printf("\n学号为%d的成绩是:%f\n",p->num,p->score);
p=p->next;
}
while(p);
}
printf("\n共有%d个数据\n",n);
}
struct student *del(struct student *head,int num){//删除元素
struct student *p1,*p2;
if(head==NULL){
printf("\n空表\n");
goto END;
}else{
p1=head;
while(num!=p1->num&&p1->next!=NULL){//不是表尾节点
p2=p1;
p1=p1->next;
}
if(p1->num==num){
if(p1==head){//判断是否为头结点
head=p1->next;//删除头结点
}
else{
p2->next=p1->next;
}
printf("\n删除%d成功",num);
n=n-1;
}
else{
printf("\n不存在的数据\n");
}
}
END:
return head;
}
//*head是链表的头指针
struct student *insert(struct student *head,struct student *stu_2){//第一个参数需要被插入的链表,第二个参数是插入的结构的地址
struct student *p0,*p1,*p2;//p0指向待插节点,p1p2遍历
p1=head;
p0=stu_2;
if(head==NULL){
head=p0;
}
else{
while((p0->num>p1->num)&&(p1!=NULL)){//开始条件为待插节点大于p0,结束条件为p1指向NULL
p2=p1;//p2跟随p1
p1=p1->next;//p1后移
if(p0->num<=p1->num){
if(p1==head){//p1若指向头结点
head=p0;//插到表头之前
}else{//插到表间
p2->next=p0;
}
p0->next=p1;
}else{//p0->num大于表中num
p1->next=p0;//插到表尾
p0->next=NULL;
}
}
}
n=n+1;
return head;
}
int main(){
struct student *stu,stu2,*p;
int a;
stu=creat(stu);
p=stu;
print(p);
printf("\n");
printf("请输入要删除学生的学号\n");
scanf("%d",&a);
print(del(p,a));
printf("请输入要插入学生的学号\n");
scanf("%d",&stu2.num);
printf("请输入分数\n");
scanf("%f",&stu2.score);
print(insert(p,&stu2));
system("pause");
return 0;
}