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

#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;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值