目录
显示
声明
这是 拼题A(PTA)《中M2019秋C入门和进阶练习集》的习题。原题在 https://pintia.cn/problem-sets/1163286449659043840/problems/1174288506294865945 (侵删)
本人的答案仅供交流学习,请勿用于当作答案来提交!
题目描述
6-26 统计专业人数 (15 point(s))
本题要求实现一个函数,统计学生学号链表中专业为计算机的学生人数。链表结点定义如下:
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
我的答案
/*================================================================
* Copyright (C) 2019 程序知路. All rights reserved.
*
* Filename :6-26-统计专业人数.c
* Author :程序知路
* E-Mail :admin@icxzl.com
* Create Date :2019年10月31日
* Description :
================================================================*/
#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 = NULL, *current = NULL, *prev = NULL;
char input[8];
while (scanf("%7s", input) == 1) {
if (!strcmp(input, "#"))
break;
if (!head) {
head = (struct ListNode*) malloc(sizeof(struct ListNode));
strncpy(head->code, input, strlen(input));
head->next = NULL;
current = head;
} else {
current = (struct ListNode*) malloc(sizeof(struct ListNode));
strncpy(current->code, input, strlen(input));
current->next = NULL;
prev->next = current;
}
prev = current;
}
return head;
}
// 有效代码
int countcs( struct ListNode *head ) {
int count = 0;
while (head) {
if (head->code[1] == '0' && head->code[2] == '2') {
++ count;
}
head = head->next;
}
return count;
}
鉴于本人的相关知识储备以及能力有限,本博客的观点和描述如有错漏或是有考虑不周到的地方还请多多包涵,欢迎互相探讨,一起学习,共同进步。
本文章可以转载,但是需要说明来源出处!
本文使用的部分图片来源于网上,若是侵权,请与本文作者联系删除: admin@icxzl.com