C/C++编程学习 - 第8周 ⑥ 程序设计:成绩查询系统

题目链接

题目描述

数学老师小y 想写一个成绩查询系统,包含如下指令:

  1. insert [name] [score],向系统中插入一条信息,表示名字为name的学生的数学成绩为score。
  2. find [name],表示查找名字为name的学生的数学成绩。
    注意有些同学可能会为了刷分多次选课,查询的时候给出最大成绩即可。学生的名字是由小写字母组成。成绩是一个 0…100 的整数。

老师找到你,想你帮他完成这个系统。

输入格式
输入若干行,每行都是insert [name] [score]或者find [name]的形式,或一行end表示输入结束。输入行数不大于 1000,每个学生名字长度不大于 20 个字符。

输出格式
对于每个查询,输出查询的学生的最高成绩,如果系统中不存在该学生,输出 −1。

Sample Input

insert zhangsan 90
insert lisi 78
insert xiaoming 86
find xiaoming
find jack
end

Sample Output

86
-1

思路

使用结构体保存学生的信息,比较字符串是"insert"还是"find"来决定是进行插入操作还是进行查询操作。

C++代码:

#include<bits/stdc++.h>
using namespace std;
typedef struct Node
{
    
    
    char name[20];
    int score;
    struct Node *next;
}Node, *List;
int Init_L(List &L)
{
    
    
    L = (List)malloc(sizeof(Node));
    if(!L)
        return 0;
    L -> next = NULL;
    return 0;
}
bool complare(int a,int b)
{
    
    
    return a > b;
}
int main()
{
    
    
    List L;
    Init_L(L);
    string operate;
    string name;
    List r, p;   
    r = L;      
    while(cin >> operate)
	{
    
    
        if(operate == "end")
            break;
        else if(operate == "insert")
		{
    
    
            char nam[20];
            int sco;
            p = (List)malloc(sizeof(Node));
            cin >> nam >> sco;
            strcpy(p -> name ,nam);
            p -> score = sco;
            r -> next = p;   
            r = p;    
            r -> next = NULL;
        }
        else if(operate == "find")
		{
    
    
            cin >> name;
            List x;    
            x = L -> next;
            int sign = 0, array[10] = {
    
    0}, i = 0, max = 0;
            while(x)
			{
    
    
                if(name == x -> name)
				{
    
    
                    array[i] = x -> score;
                    if(max < array[i]) max = array[i];
                    i++;
                    sign = 1;
                }
                x = x -> next;
            }
            if(sign == 1) cout << max << endl;
            if(sign == 0) cout << "-1" << endl;
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_44826711/article/details/113079946
今日推荐