单向链表实现学生信息管理系统

学习记录

#include<stdio.h>
#include<stdlib.h>

struct student
{
    int id;
    int score;
    struct student *next;
};
typedef struct student stu;

stu *cl(stu *head)//创
{
    head=(stu*)malloc(sizeof(stu));
    if(head==NULL)
    {
        printf("内存分配失败!\n");
        exit(0);
    }
    head->next=NULL;
    return head;
}

stu *al(stu *head,int id,int score)//加
{
    stu *p,*pr=head;
    p=(stu*)malloc(sizeof(stu));
    if(p==NULL)
    {
        printf("内存分配失败!\n");
        exit(0);
    }
    p->id=id;
    p->score=score;
    while(pr->next!=NULL)
        pr=pr->next;
    pr->next=p;//切勿写反
    p->next=NULL;//不写就会报错
    return head;
}

stu *il(stu *head,int pos,int id,int score)//插
{
    stu *p,*pr=head;
    p=(stu*)malloc(sizeof(stu));
    if(p==NULL)
    {
        printf("内存分配失败!\n");
        exit(0);
    }
    p->id=id;
    p->score=score;
    p->next=NULL;
    if(pos==-1)
    {
        p->next=head->next;
        head->next=p;
    }
    else
    {
        while(pr->id!=pos&&pr->next!=NULL)
        {
            pr=pr->next;
        }
        if(pr->id==pos)
        {
            p->next=pr->next;
            pr->next=p;
        }
    }
    return head;
}

stu *dl(stu *head,int id)//删
{
    stu *p,*pre;
    p=head->next;
    pre=head;
    while(p->id!=id&&p->next!=NULL)
    {
        pre=pre->next;
        p=p->next;
    }
    if(p->id==id)
    {
        pre->next=p->next;
        free(p);
    }
    return head;
}

int fl(stu *head,int id)//查
{
    int score;
    stu *p=head;
    while(p->id!=id&&p->next!=NULL)
    {
        p=p->next;
    }
    if(p->id==id)
    {
        score=p->score;
        return score;
    }
    return -1;
}

void disp(stu *head)//遍历
{
    stu *p=head->next;
    printf("当前所有学生信息如下:\n");
    while(p!=NULL)
    {
        printf("学号:%-3d成绩:%-3d\n",p->id,p->score);
        p=p->next;
    }
}

int main()
{
    int id;
    int score;
    int pos;
    char c;
    stu *head=NULL;
    head=cl(head);
    printf("请输入学生学号和成绩:\n");
    scanf("%d%d",&id,&score);
    head=al(head,id,score);
    printf("创建成功,请输入\"Y\"继续创建,输入其他字符进入下一步。\n");
    getchar();
    c=getchar();
    while(c=='Y')
    {
        printf("请输入学生学号和成绩:\n");
        scanf("%d%d",&id,&score);
        head=al(head,id,score);
        printf("创建成功,请输入\"Y\"继续创建,输入其他字符进入下一步。\n");
        getchar();
        c=getchar();
    }
    printf("请输入插入学生的学号和成绩:\n");
    scanf("%d%d",&id,&score);
    printf("请输入要将该学生插入到哪位学生之后(输入其学号,-1代表插入到最前面):\n");
    scanf("%d",&pos);
    head=il(head,pos,id,score);
    printf("插入成功。\n");
    disp(head);
    printf("请输入要删除学生的学号:\n");
    scanf("%d",&id);
    printf("被删除的学生的成绩为:%d\n",fl(head,id));
    head=dl(head,id);
    disp(head);
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值