查询成绩(要求用链表完成)

Description
知道如何创建链表了。
本题继续要求用链表完成。输入同学成成绩后,现在再输入1个同学的姓名,输出该同学的成绩。

Input
输入一些学生的信息,每个学生信息一行,分别为学号、姓名和成绩,中间用空格隔开,其中学号和成绩均为整数,姓名为不超过15个仅包含大小写字母的字符。
如果输入的一行是非正整数时,表示结束
在成绩结束后,输入一行,为一个同学的姓名

Output
输出一个整数,表示该同学的成绩

Sample Input
1001 xiangwang 90
1002 xiaoli 85
1003 xiaohong 97
1004 xiaoma 76
-1
xiaoli
Sample Output
85

本题某种程度上说很死板,我很确定代码没错,但就是超时,而代码已经缩减到我能做到的最少了,如果坚持用cin输入基本就会超时,只能用scanf。但让我获得了一个很好的知识点,在c++中cin做的操作比scanf要来的多。

#include<iostream>
#include<malloc.h>
#include<cstring>
using namespace std;
struct node {
	int score;
	char name[15];
	struct node *next;
};//struct结构体
struct node * Create_Stu_Doc() {
	struct node *head,*tail,*p;//头尾和p指针
	int num,score;
	char name[15];
	head = tail =NULL;
	scanf("%d", &num);
	while(num > 0) {
		scanf("%s%d",name,&score);
		p = (struct node *) malloc(sizeof(node));
		p->score=score;
		strcpy(p->name,name);
		p->next = NULL;
		if(head==NULL) head=p;//这边还能再简化但代码更繁琐,能通过就不改了
		else tail->next=p;
		tail = p;
		scanf("%d", &num);
	}
	return head;
};
int main() {
	struct node *head,*p;
	char name[15];
	head=Create_Stu_Doc();
	scanf("%s",name);
	for(p=head; p!=NULL; p=p->next) {
		if(strcmp(p->name,name)==0) {
			printf("%d",p->score);
		}

	}
	return 0;
}

发布了127 篇原创文章 · 获赞 113 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/z2431435/article/details/104604627
今日推荐