代码如下:
typedef struct _STU //定义的学生信息结构体
{
int id;
char name[32];
char sex;
int age;
struct _STU *next;
}STU,*PSTU;
void DeleteHead(PSTU * ppHead) //头删法删除数据
{
if (*ppHead != NULL)
{
PSTU pPos = *ppHead;
*ppHead = pPos->next;
free(pPos);
pPos = NULL;
}
}
void inserthead(PSTU *pphead, int id, char name[], char s,int age)//头插法插入数据
{
PSTU pNew = (PSTU)malloc(sizeof(STU));
pNew->id = id;
strcpy(pNew->name, name);
pNew->sex = s;
pNew->age = age;
pNew->next=*pphead;
*pphead = pNew;
}
void deletesameage(PSTU *pphead,int age)//删除其中与输入年龄相同的学生数据
{
PSTU pPos = NULL;
PSTU t = NULL;
pPos = *pphead;
while (pPos->next != NULL)
{
if (pPos!=NULL&&pPos->next->age == age)
{
t = pPos->next;
pPos->next = pPos->next->next;
}
else pPos = pPos->next;
}
if ((*pphead)->age == age)
{
DeleteHead(pphead);
}
}
void show(const PSTU head)//输出
{
PSTU pos = head;
while (pos!=NULL)
{
printf("%d %s %c %d\n", pos->id, pos->name, pos->sex, pos->age);
pos = pos->next;
}
}
int main()
{
PSTU head = NULL;
int age;
printf("请输出您要删除的年龄:");
scanf("%d",&age);
inserthead(&head,9001, "强国力", 'M', 22);
inserthead(&head, 9002, "叶良辰", 'M', 20);
inserthead(&head, 9003, "龙傲天", 'M', 22);
inserthead(&head, 9004, "尼古拉斯·富贵", 'f', 20);
inserthead(&head, 9005, "李狗蛋", 'f', 22);
inserthead(&head, 9006, "南宫问天", 'f', 20);
show(head);
puts("---------------------------");
deletesameage(&head, 20);
show(head);
return 0;
}
结果如图所示,我输入的年龄为20,将其中年龄为20的学生数据全部删除。