C/C++ Programming Learning-Week 8 ⑥ Program Design: Score Inquiry System

Topic link

Title description

Mathematics teacher Xiaoy wants to write a score query system, which contains the following instructions:

  1. insert [name] [score], insert a message into the system, indicating that the math score of the student whose name is name is score.
  2. find [name] means to find the mathematics score of the student whose name is name.
    Note that some students may choose courses multiple times in order to score points, and just give the maximum score when inquiring. The student's name is composed of lowercase letters. The grade is an integer from 0…100.

The teacher found you and wanted you to help him complete this system.

Input format
Input several lines, each line is in the form of insert [name] [score] or find [name], or a line of end means the end of input. The number of input lines is not more than 1000, and the length of each student's name is not more than 20 characters.

Output format
For each query, output the highest score of the queried student. If the student does not exist in the system, output −1.

Sample Input

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

Sample Output

86
-1

Ideas

Use the structure to save the student's information, compare whether the string is "insert" or "find" to decide whether to insert or query.

C++ code:

#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;
}

Guess you like

Origin blog.csdn.net/qq_44826711/article/details/113079946