刚学完链表,编了一个程序,为什么运行的那么慢呢?
#include<stdio.h>#include<malloc.h>
#define len sizeof(struct student)
struct student
{ long num;
float score;
struct student *next;
};
struct student *create(void)
{ struct student *p1,*p2,*head;
int n=0;
p1=p2=(struct student *)malloc(len);
//scanf("%ld,%f",&p1->num,&p1->score);
printf("请输入学号:");
scanf("%ld",&p1->num);
printf("请输入成绩:");
scanf("%f",&p1->score);
head=NULL;
while(p1->num!=0)
{ n++;
if(n==1) head=p1;
else p2->next=p1;
p2=p1;
p1=(struct student *)malloc(len);
//scanf("%ld,%f",&p1->num,&p1->score);
printf("请输入学号:");
scanf("%ld",&p1->num);
if(p1->num!=0)
{
printf("请输入成绩:");
scanf("%f",&p1->score);
}
}
p2->next=NULL;
return(head);
}
void output(struct student *head)
{ struct student *p;
p=head;
if(head!=NULL)
do
{ printf("%ld %.0f\n",p->num,p->score);
p=p->next;
}while(p!=NULL);
}
struct student *shanchu(struct student *head,long n)
{
struct student *p1,*p2;
if(head==NULL) printf("错误");
p1=head;
while(p1->num!=n&&p1->next!=NULL)
{ p2=p1; p1=p1->next;}
if(n==p1->num)
{ if(head==p1) head=p1->next;
else p2->next=p1->next;
}
else printf("not found\n");
return(head);
}
struct student *add(struct student *head,struct student *stu)
{ struct student *p1,*p2,*p0;
p1=head;p2=stu;
if(p1==NULL) { head=p2;p2->next=NULL;}
else {
while(p2->num>p1->num&&p1->next!=NULL)
{p0=p1;p1=p1->next;}
if(p2->num<=p1->num)
{
if(head==p1) {head=p2; p2->next=p1;}
else {p0->next=p2; p2->next=p1; }
}
else {p1->next=p2; p2->next=NULL; }
}
return(head);
}
void main()
{ long n;
struct student *p,*head,*p3;
printf("请输入数据(输入0可以结束):\n");
head=create();
p=head;
printf("输出数据:\n");
output(p);
printf("请输入要删除的学号:");
scanf("%ld",&n);
while(n!=0)
{ head=(struct student *)shanchu(p,n);
p=head;
printf("请输入要删除的学号:");
scanf("%ld",&n);
}
printf("显示数据:\n");
output(p);
printf("请输入要添加的学生及其成绩:\n");
p3=(struct student *)malloc(len);
//scanf("%ld,%f",&p3->num,&p3->score);
printf("请输入学号:");
scanf("%ld",&p3->num);
printf("请输入成绩:");
scanf("%f",&p3->score);
while(p3->num!=0)
{ head=(struct student *)add(p,p3);
p=head;
p3=(struct student *)malloc(len);
printf("请输入要添加的学生及其成绩:\n");
//scanf("%ld,%f",&p3->num,&p3->score);
printf("请输入学号:");
scanf("%ld",&p3->num);
if(p3->num!=0)
{
printf("请输入成绩:");
scanf("%f",&p3->score);
}
}
output(p);
}