C语言单向链表操作:创建学生成绩链表并删除低于分数线的节点

本题要求实现两个函数:

  1. createlist:用于将学生成绩组织成单向链表。
  2. deletelist:用于从链表中删除成绩低于某分数线的学生结点。

函数接口定义

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

链表节点结构

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

函数功能

  • createlist:利用 scanf 从输入中获取学生的信息(学号、姓名、成绩),将其组织成单向链表,并返回链表头指针。输入为若干个学生的信息,当输入学号为 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

代码实现

struct stud_node *createlist()
{
    struct stud_node *head, *tail, *p;
    head = tail = NULL;
    int num, score;
    char name[20];
    scanf("%d", &num);
    while (num)
    {
        scanf("%s%d", name, &score);
        p = (struct stud_node *)malloc(sizeof(struct stud_node));
        p->num = num, p->score = score;
        strcpy(p->name, name);
        p->next = NULL;
        if (!head)
            head = p;
        else
            tail->next = p;
        tail = p;
        scanf("%d", &num);
    }
    return head;
}

struct stud_node *deletelist(struct stud_node *head, int min_score)
{
    struct stud_node *p, *q;
    while (head && head->score < min_score)
    {
        p = head;
        head = head->next;
        free(p);
    }
    if (!head)
        return NULL;
    p = head, q = head->next;
    while (q)
    {
        if (q->score < min_score)
        {
            p->next = q->next;
            free(q);
            q = p->next;
        }
        else
        {
            p = q;
            q = q->next;
        }
    }
    return head;
}

原文地址: https://www.cveoy.top/t/topic/nydM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录