第三-五周|2-2 学生成绩链表处理

本题要求实现两个函数,一个将输入的学生成绩组织成单向链表;另一个将成绩低于某分数线的学生结点从链表中删除。

函数接口定义:

 

struct stud_node *createlist(); struct stud_node *deletelist( struct stud_node *head, int min_score );

函数createlist利用scanf从输入中获取学生的信息,将其组织成单向链表,并返回链表头指针。链表节点结构定义如下:

 

struct stud_node { int num; /*学号*/ char name[20]; /*姓名*/ int score; /*成绩*/ struct stud_node *next; /*指向下个结点的指针*/ };

输入为若干个学生的信息(学号、姓名、成绩),当输入学号为0时结束。

函数deletelist从以head为头指针的链表中删除成绩低于min_score的学生,并返回结果链表的头指针。

裁判测试程序样例:

 

#include <stdio.h> #include <stdlib.h> struct stud_node { int num; char name[20]; int score; struct stud_node *next; }; struct stud_node *createlist(); struct stud_node *deletelist( struct stud_node *head, int min_score ); int main() { int min_score; struct stud_node *p, *head = NULL; head = createlist(); scanf("%d", &min_score); head = deletelist(head, min_score); for ( p = head; p != NULL; p = p->next ) printf("%d %s %d\n", p->num, p->name, p->score); return 0; } /* 你的代码将被嵌在这里 */

输入样例:

1 zhang 78
2 wang 80
3 li 75
4 zhao 85
0
80

输出样例:

2 wang 80
4 zhao 85

代码长度限制

16 KB

时间限制

400 ms

内存限制

64 MB

以下是答案

struct stud_node *createlist()
{
    struct stud_node *head, *tail, *s;
    head = (struct stud_node*)malloc(sizeof(struct stud_node));
    head->next = NULL;
    tail = head;
    //将尾节点tail指向了头节点head,初始时头尾节点是同一个节点。
    while (1)//如果学生编号为0,表示输入结束,此时跳出循环。
    {
        s = (struct stud_node*)malloc(sizeof(struct stud_node));
        scanf("%d", &s->num);
        if (s->num == 0)
            break;
        scanf("%s", s->name);
        scanf("%d", &s->score);
        s->next = NULL;
        tail->next = s;
        tail = s;
//将尾节点tail的next指针指向新节点s,将新节点s成为链表中的最后一个节点,并更新尾节点tail为新节点
    }
    
    return head;
}

struct stud_node *deletelist(struct stud_node *head, int min_score)
//接受一个头节点head和一个最小成绩min_score作为参数,并返回删除后的链表头部指针。
{
    struct stud_node *p, *n;
    p = head->next;
    
    while (p != NULL)
    {
        if (p->score < min_score)
        {
            n = head;
            while (n->next != p)
                n = n->next;
//n = n->next是用来移动指针n到下一个节点,作用是遍历链表
            n->next = p->next;//n->next = p->next的作用是将指针n所指向的节点的next指针指向节 
 //点p的下一个节点。有删除作用
            struct stud_node *temp = p;
            p = p->next;//将指针p指向当前节点的下一个节点。当删除一个节点后,我们需要继续遍历下 
 //一个节点,所以需要将指针p指向当前节点的下一个节点。
            free(temp);
        }
        else
        {
            n = p;
            p = p->next;
//n = p用于保存当前节点的引用,然后p = p->next将指针p移动到下一个节点。,而n指针的移动通过他的next指针来实现,设置n的next指针为p的next指针,跳过当前节点。
        }
    }
    
    return head->next;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值