建立一个链表,每个结点包括学号姓名性别年龄,输入一个年龄,如果链表中的结点包含这个年龄,则将此节点

2025-06-29 11:49:16
推荐回答(1个)
回答1:

#include 
#include 
#include 

typedef struct student {
unsigned id; // 学号
char name[20];
unsigned age;
struct student *next;
}*LinkList,*pNode;

LinkList GetEmptyList() {
LinkList head = (pNode)malloc(sizeof(struct student));
head->next = NULL;
return head;
}

void AddNode(LinkList head, pNode newnode) {
newnode->next = head->next;
head->next = newnode;
}

void WhatName(LinkList head, unsigned age) {
pNode p = head,q;
while(p->next) {
if(p->next->age == age) {
q = p->next;
p->next = q->next;
free(q);
}
else p = p->next;
}
}

void ShowList(LinkList head) {
pNode p = head->next;
while(p) {
printf("%u\t%s\t%u\n",p->id,p->name,p->age);
p = p->next;
}
}

int main() {
unsigned id,age;
char name[20];
pNode newnode;
LinkList head = GetEmptyList();
printf("学号 姓名 年龄(q to quit):");
while(scanf("%u%s%u",&id,name,&age) == 3) {
newnode = (pNode)malloc(sizeof(struct student));
newnode->id = id;
newnode->age = age;
strcpy(newnode->name,name);
AddNode(head,newnode);
printf("学号 姓名 年龄(q to quit):");
}
ShowList(head);
WhatName(head,21); // 删除年龄为21周岁的学生(荒唐)
ShowList(head);
return 0;
}