#include<stdio.h.>
#include<malloc.h>
#define len sizeof(struct student)
struct student
{
long num;
float score;
struct student *next;
};
int n;
struct student *xin()
{
struct student *insert(struct student *head,struct student *stud);
struct student *head;
struct student *p1,*p2;
n=0;
p1=p2=(struct student *)malloc(len);
printf("请输入第1组数据");
scanf("%ld%f",&p1->num,&p1->score);
head=NULL;
while(p1->num!=0)
{
head=insert(head,p1);//head=一定不能省
p2=p1;
p1=(struct student *)malloc(len);
printf("请输入第%d组数据",n+1);
scanf("%ld%f",&p1->num,&p1->score);
}
return (head);
}
struct student *del(struct student *head,long num)
{
struct student *p1,*p2;
if(head==NULL)
{
printf("
链表是空的
");
return (head);
}
else
{
p1=head;
while(num!=p1->num&&p1->next!=NULL)
{
p2=p1;
p1=p1->next;
}
if(num==p1->num)
{
if(p1==head)head=p1->next;
else p2->next=p1->next;//把p1抠出来
printf("delete:%ld
",num);
n--;
}
else
printf("%ld not be found",num);
return (head);
}
}
struct student *insert(struct student *head,struct student *stud)
{
struct student*p0,*p1,*p2;
p1=head;
p0=stud;
if(head==NULL)
{
head=p0;
p0->next=NULL;
}
else
{
while((p0->num>p1->num)&&(p1->next!=NULL))
{
p2=p1;
p1=p1->next;
}
if(p0->num<=p1->num)
{
if(head==p1)head=p0;//插入点在开始
else p2->next=p0;//插入点在中间
p0->next=p1;
}
else
{
p1->next=p0; //插入点在链表末尾
p0->next=NULL;
}
}
n++;
return (head);
}
int print(struct student *head)
{
struct student *p;
printf("
一共有%d条记录
",n);
p=head;
if(head!=NULL)
{
do
{
printf("%ld %5.2f
",p->num,p->score);
p=p->next;
}
while(p!=NULL);
}
}
int main()
{
struct student *head,*stud;
long delnum;
printf("请输入初始链表:
");
head=xin();
print(head);
printf("请输入删除数字:");
scanf("%ld",&delnum);
while(delnum!=0)
{
head=del(head,delnum);
print(head);
printf("please input the delnum:");
scanf("%ld",&delnum);
}
printf("
请输入插入记录:");
stud=(struct student*)malloc(len);
scanf("%ld%f",&stud->num,&stud->score);
while(stud->num!=0)
{
head=insert(head,stud);
print(head);
printf("
请输入插入记录:");
stud=(struct student*)malloc(len);
scanf("%ld%f",&stud->num,&stud->score);
}
return 0;
}