刚编了个链表程序,建立一个链表,每个结点包括:学号,姓名,性别,年龄。输入一个年龄,如果链表中的结点所含的年龄等于此年龄,则将此结点删除。之中遇到个问题,不管输入的该年龄在链表的有没有,有一个或者是几个,还是全部,红色部分的for语句都要循环m(原链表的总结点数)次,实在想不出什么法子让它最优化,所以我干脆管它黑猫白猫都循环m次。大家出出点子,谢谢了!
#include<malloc.h>
#define LEN sizeof(struct student)
struct student
{
long num;
char name[20];
char sex[5];
int age;
struct student *next;
};
int m;
int flag=0;
struct student *creat(void)
{
struct student *head,*p1,*p2;
p1=p2=(struct student*)malloc(LEN);
scanf("%ld%s%s%d",&(p1->num),p1->name,p1->sex,&(p1->age));
head=NULL;
m=0;
while(p1->num!=NULL)
{m=m+1;
if(head==NULL)head=p1;
else p2->next=p1;
p2=p1;
p1=(struct student*)malloc(LEN);
scanf("%ld%s%s%d",&(p1->num),p1->name,p1->sex,&(p1->age));
}
p2->next=NULL;
return head;
}
struct student *deleteage(struct student *head,int n)
{
struct student *p1,*p2;
p1=head;
while(n!=p1->age&&p1!=NULL)
{
p2=p1;
p1=p1->next;
}
if(n==p1->age)
{
if(p1==head)head=p1->next;
else
p2->next=p1->next;
flag=flag+1;
}
return(head);
}
main()
{
struct student *head,*p;
int i,AGE;
printf("\ndata [num name sex age]:\n");
head=creat();
printf("\nInput age delete: age=");
scanf("%d",&AGE);
for(i=0;i<m;i++)
head=deleteage(head,AGE);
if(flag==0)printf("\nage %d not been found!",AGE);
else
{
p=head;
printf("\noutput data after deleted:\nnum name sex age\n");
while(p!=NULL)
{
printf("%ld%8s%6s%6d\n",p->num,p->name,p->sex,p->age);
p=p->next;
}
}
getch();
}