美文网首页
【MAC 上学习 C++】Day 55-6. 实验11-2-7

【MAC 上学习 C++】Day 55-6. 实验11-2-7

作者: RaRasa | 来源:发表于2019-10-18 19:15 被阅读0次

实验11-2-7 统计专业人数 (15 分)

1. 题目摘自

https://pintia.cn/problem-sets/13/problems/606

2. 题目内容

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

struct ListNode {
char code[8];
struct ListNode *next;
};
这里学生的学号共7位数字,其中第2、3位是专业编号。计算机专业的编号为02。

函数接口定义:

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

输入样例:

1021202
2022310
8102134
1030912
3110203
4021205

输出样例:

3

3. 源码参考
#include <iostream>
#include <stdlib.h>
#include <string.h>

using namespace std;

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

struct ListNode *createlist(); 
int countcs( struct ListNode *head );

int main()
{
    struct ListNode  *head;

    head = createlist();
    cout << countcs(head) << endl;
    
    return 0;
}

struct ListNode *createlist()
{
  struct ListNode *p, *h, *t;
  char code[8];

  h = t = NULL;
  cin >> code;
  while(code[0] != '#')
  {
    p = (struct ListNode*)malloc(sizeof(struct ListNode));
    
    strcpy(p->code, code);
    p->next = NULL;
    
    if(h == NULL)
    {
      h = p;
    }
    else
    {
      t->next = p;
    }

    t = p;
    
    cin >> code;
  }
  
  return h;
}

int countcs( struct ListNode *head )
{
  char code[8];
  int cnt = 0;

  struct ListNode *p = head;
  while (p) 
  {
    sprintf(code, "%s", p->code);
    if((code[1] == '0') && (code[2] == '2'))
    {
      cnt++;
    }
    p = p->next;
  }

  return cnt;
}

相关文章

网友评论

      本文标题:【MAC 上学习 C++】Day 55-6. 实验11-2-7

      本文链接:https://www.haomeiwen.com/subject/fkbhmctx.html