[PTA]实验11-2-7 统计专业人数

Posted Spring-_-Bear

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[PTA]实验11-2-7 统计专业人数相关的知识,希望对你有一定的参考价值。

本题要求实现一个函数,统计学生学号链表中专业为计算机的学生人数。链表结点定义如下:

struct ListNode {
    char code[8];
    struct ListNode *next;
};

这里学生的学号共7位数字,其中第2、3位是专业编号。计算机专业的编号为02。

函数接口定义:

int countcs( struct ListNode *head );

其中head是用户传入的学生学号链表的头指针;函数countcs统计并返回head链表中专业为计算机的学生人数。

裁判测试程序样例:

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

struct ListNode {
    char code[8];
    struct ListNode *next;
};

struct ListNode *createlist(); /*裁判实现,细节不表*/
int countcs( struct ListNode *head );

int main()
{
    struct ListNode  *head;

    head = createlist();
    printf("%d\\n", countcs(head));

    return 0;
}

/* 你的代码将被嵌在这里 */

输入样例:

1021202
2022310
8102134
1030912
3110203
4021205
#

输出样例:

3
  • 提交结果:

在这里插入图片描述

  • 源码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct ListNode {
    char code[8];
    struct ListNode* next;
};

struct ListNode* createlist(); /*裁判实现,细节不表*/
int countcs(struct ListNode* head);

int main()
{
    struct ListNode* head;

    head = createlist();
    printf("%d\\n", countcs(head));

    return 0;
}

/* 你的代码将被嵌在这里 */
struct ListNode* createlist()
{
    struct ListNode* head, * tail, * temp;      // 头节点、尾节点、临时节点

    head = tail = temp = NULL;

    char code[8];

    scanf("%s", &code);

    // 输入以'#'结束
    while (strcmp(code,"#")!=0)
    {
        // 为临时节点分配内存
        temp = (struct ListNode*)malloc(sizeof(struct ListNode));
        // 临时节点指向空
        temp->next = NULL;
        // 存入数据
        strcpy(temp->code, code);

        // 将第一个数据存入头结点
        if (head == NULL)
        {
            head = temp;
        }
        else
        {
            // 将临时节点连接到链表尾
            tail->next = temp;
        }
        
        // 更新尾节点
        tail = temp;

        scanf("%s", &code);
    }

    return head;
}

int countcs(struct ListNode* head)
{
    int count = 0;

    // 链表为空,返回0
    if (head == NULL)
    {
        return count;
    }

    while (head)
    {
        char code[8];

        // 将链表中的数据存入临时字符数组
        strcpy(code, head->code);

        // 符合计算机专业代码"02"
        if (code[1] == '0' && code[2] == '2')
        {
            count++;
        }

        head = head->next;
    }

    return count;
}

以上是关于[PTA]实验11-2-7 统计专业人数的主要内容,如果未能解决你的问题,请参考以下文章

C博客作业--指针

C博客作业--指针

C博客作业--指针

PTA的Python练习题-第4章-7 统计学生平均成绩与及格人数

C博客作业--指针

C博客作业--指针