9.1建立一个链表,每个结点包括学号、姓名性别年龄。输入一个年龄,如果链表 中的结点所包含的年龄等于此年龄,则将此结点删去
#include<stdio.h> #include<stdlib.h> #include<string.h>
typedef struct node{ int number; char name[20]; char sex; int age; struct node *next; }Node,*LinkList;
LinkList InitList(){ LinkList head; head=(Node*)malloc(sizeof(Node)); head->next=NULL; return head; }
void CreatByRear(LinkList head){ Node *r,*s; int number; char name[20]; char sex; int age; r=head; printf("请输入学生信息:\n"); while(1){ printf("输入学号、姓名、性别、年龄:\n"); scanf("%d %s %c %d",&number,name,&sex,&age); if(number==0){ break; } s=(Node*)malloc(sizeof(Node)); s->number=number; strcpy(s->name,name); s->sex=sex; s->age=age; r->next=s; r=s; } r->next=NULL; }
void Delete(Node *head,int ag){ Node *pre,*p; pre=head; p=head->next; while(p){ if(p->age==ag){ pre->next=p->next; free(p); } pre=p; p=p->next; } if(!p){ printf("未找到相关数据\n"); } }
void OutPut(LinkList head){ Node *p; p=head->next; printf("\n****学生信息如下*****\n"); while(p){ printf("学号:%d\t姓名:%s\t性别:%c\t年龄:%d\t\n",p->number,p->name,p->sex,p->age); p=p->next; } }
int main(){ LinkList h; h=InitList(); CreatByRear(h); OutPut(h); int ag; printf("输入删除的年龄:\n"); scanf("%d",&ag); Delete(h,ag); printf("删除后:\n"); OutPut(h); return 0; }