#include<stdio.h>
#include<stdlib.h>
#define LEN sizeof(struct Student)
struct Student
{
int num;
char name[20];
char sex;
int age;
struct Student *next;
};
int main()
{
struct Student *p1,*p2,*head,*p;
int a;
printf("input students'num,name,sex,age:\n");
p=head=p2=p1=(struct Student*)malloc(LEN);
scanf("%d %s %c %d",&(p1->num),p1->name,&(p1->sex),&(p1->age));
while((p1->num )!= 0)
{
p1=(struct Student*)malloc(LEN);
scanf("%d %s %c %d", &(p1->num), p1->name, &(p1->sex), &(p1->age));
p2->next=p1;
p2=p1;
}
free(p2);
p2=NULL;
do
{
printf("%03d %s %c %d\n",p->num,p->name,p->sex,p->age);
p=p->next;
}while(p!=NULL);
printf("input a num:\n");
scanf("%d",&a);
p=head;
do
{
if(a==p->age)
{
if(p==head)
{
free(p);
head=p->next;
}
else if(p->next==NULL)
{
free(p);
p=NULL;
}
else
{
free(p);
p=p->next;
}
}
p=p->next;
}while(p!=NULL);
p=head;
if(head!=NULL)
{
do
{
printf("%03d %s %c %d\n",p->num,p->name,p->sex,p->age);
p=p->next;
}while(p!=NULL);
}
return 0;
}
貌似输入最后一个学生的年龄删除不了。。
追答我知道有这个问题,这个可以自己调,因为你的do while()是以p==NULL结束,
所以在上面的if else 中里面各添加一个p=p2->next;就行了。因为那时候把p2移动了,p没有跟着移。
这都是逻辑问题。其实还有别的改法。
比如把 p=p2->next 放到最后 ,然后再放一个p=p2->next初始化在do的前面也应该是可以解决的。
也可以想想别的方法。