写一程序用来按学生姓名查询其排名和平均成绩。n个学生的排名,姓名和成绩数据从键盘输入。
查询可连续进行, 直到键入查询关键字为0时结束程序。
【输入说明】
输入第一行1个整数,表示n。接下来n行输入表示n名学生的信息。之后输入的数据表示要查询的学生姓名。
查询关键字为0时结束程序。
【输出说明】
若能查询到数据,则显示排名、姓名和成绩,数据间使用空格间隔。若不能查询,则显示“Not found XXX!”。
【输入样例】
2
1 60 zhangsan
2 50 lisi
zhangsan
wangwu
0
【输出样例】
1 zhangsan 60
Not found wangwu!
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define LEN sizeof(struct student)
struct student
{
int rank;
char name[10];
int score;
struct student* next;
};
struct student* create(int n);//创建n个节点的链表
struct student* find_list(); //建立需要查询的数据的链表
void find_print(struct student*headnode_a, struct student* headnode_b); //查询并且打印链表
int main()
{
int n;
printf("请输入创建的名单个数\n");
scanf("%d", &n);
struct student* list_A = create(n);
struct student* list_B = find_list();
find_print(list_A,list_B);
return 0;
}
struct student* create(int n)//创建n个节点的链表
{
struct student* headnode = (struct student*)malloc(LEN);
struct student* pmove = (struct student*)malloc(LEN);
headnode->next = NULL;
pmove = headnode;
for (int i = 0; i < n; i++)
{
struct student* newnode = (struct student*)malloc(LEN);
pmove->next = newnode;
newnode->next = NULL;
pmove = pmove->next;
}
pmove = headnode;
printf("请输入学生学号\t平均成绩\t姓名\t\n");
while (pmove->next)
{
scanf("%d %d%s", &pmove->rank, &pmove->score, &pmove->name);
pmove = pmove->next;
}
return headnode;
}
struct student* find_list() //建立需要查询的数据的链表
{
struct student* headnode = (struct student*)malloc(LEN);
struct student* pmove = (struct student*)malloc(LEN);
headnode->next = NULL;
pmove = headnode;
printf("请输入需要查找的学生名字,若结束,则输入‘0’\n");
while (1)
{
struct student* newnode = (struct student*)malloc(LEN);
pmove->next = newnode;
newnode->next = NULL;
scanf("%s", &pmove->name);
if (!strcmp((pmove->name),"0"))
{
break;
}
pmove = pmove->next;
}
return headnode;
}
void find_print(struct student* headnode_a, struct student* headnode_b) //查询并且打印链表
{
struct student* pmove_a = (struct student*)malloc(LEN);
struct student* pmove_b = (struct student*)malloc(LEN);
pmove_b = headnode_b;
printf("查询结果:\n");
while (pmove_b) //遍历b链表(待查询)
{
pmove_a = headnode_a;
int i = 0; //判断: 0的含义 遍历a链表没查到
while (pmove_a) //遍历a链表
{
if (!strcmp(pmove_a->name, pmove_b->name))
{
i = 1; //判断 1的含义 查到了
printf("%d %s %d\n", pmove_a->rank, pmove_a->name, pmove_a->score);
}
pmove_a = pmove_a->next;
}
if (i == 0)
{
printf("Not found %s!\n", pmove_b->name);
}
if (!strcmp(pmove_b->next->name, "0"))//如果下一个名字是 ‘0’ 结束标志 则结束循环
{
break;
}
pmove_b = pmove_b->next;
}
}
运行结果