要求
读入 n(>0)名学生的姓名、学号、成绩,分别输出成绩最高和成绩最低学生的姓名和学号。
实现方法
看到这道题,第一眼想到用结构体+链表来实现。
写完之后提交,只有第一个测试点通过。就琢磨发现流程没有问题,自己测试几个数据都能通过。最后,突然发现可能是结构体中字符串长度定义小了,改成20果然通过了
实现代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct Student{//定义结构体
char name[20];
char id[20];
int gold;
struct Student * next;
}Student;
int main(){
struct Student * L;
struct Student * Lhead;
struct Student * p;
L = (struct Student *) (malloc(sizeof(struct Student)));
Lhead = L;
p = L;
int n;
int a,b,c,d;
scanf("%d",&n);
for(int i = 0; i<n; i++){
struct Student * q;
q = (struct Student*)(malloc(sizeof(struct Student)));
scanf("%s",&(q->name));
scanf("%s",&(q->id));
scanf("%d",&(q->gold));
p->next = q;
p = q;
}
p = L->next;
a = p->gold;
b = 0;
c = p->gold;
d = 0;
for(int i = 0;i<n;i++){
if(a<p->gold){
a = p->gold;
b = i;
}
if(c>p->gold){
c = p->gold;
d = i;
}
p = p->next;
}
p = L->next;
int i = 0;
while(i<b){
p = p->next;
i++;
}
printf("%s %s\n",p->name,p->id);
p = L->next;
i = 0;
while(i<d){
p = p->next;
i++;
}
printf("%s %s",p->name,p->id);
return 0;
}