您的位置:首页 > 其它

一个学生的信息是:姓名,学号,性别,年龄等信息,用一个链表,把这些学生信息连在一起, 给出一个age, 在 链表中删除学生年龄等于age的学生信息。

2016-07-01 10:01 686 查看
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXSIZE 10

typedef struct stu{
char name[MAXSIZE];
int num;
char sex[2];
int age;
struct stu * next;
}StuInfo;

StuInfo * createStuForm(int n){
StuInfo * head,* q,* p;
head = (StuInfo *)malloc(sizeof(StuInfo));
head->next = NULL;
q = head;
for(int i=0;i<n;i++){
p = (StuInfo *)malloc(sizeof(StuInfo));
printf("请输入学生的姓名。\n");
scanf("%s",&p->name);
printf("请输入学生的学号。\n");
scanf("%d",&p->num);
printf("请输入学生的性别。\n");
scanf("%s",&p->sex);
printf("请输入学生的年龄。\n");
scanf("%d",&p->age);
p->next = NULL;
q->next = p;
q = p;
}
return head;
}

void print(StuInfo * head){
StuInfo * p;
p = head->next;
printf("姓名 学号 性别 年龄\n");
while(p != NULL){
printf("%s  %d    %s   %d",p->name,p->num,p->sex,p->age);
printf("\n");
p = p->next;
}
}

deleteStu(StuInfo * head,int inAge){
StuInfo * p,* q;
q = head;
p = head->next;
while(p != NULL){
if(p->age != inAge){
q = q->next;
p = p->next;
}else{
q->next = p->next;
free(p);
break;
}
}
if(p == NULL){
printf("学生表年龄字段没有该值!\n");
}
}
/* 第二种方式删除学生信息
void deleteStu(StuInfo * head,int inAge){
StuInfo * p,* q;
p = head->next;
while(p->age != inAge){
q = p;
p = p->next;
}
if(p == NULL){
printf("学生表年龄字段没有该值!\n");
}else{
q->next = p->next;
free(p);
}
}
*/
int main(){
int n,inAge;
StuInfo * head;
printf("请输入学生的个数。\n");
scanf("%d",&n);
head = createStuForm(n);
print(head);
printf("若年龄与给定的年龄相同,则删除该学生。\n");
printf("请输入年龄。\n");
scanf("%d",&inAge);
deleteStu(head,inAge);
printf("学生表中的数据:\n");
print(head);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: