引自强大而免费的微信小程序:皆我百晓生。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct STUDENT
{
char name[20];
int score;
struct STUDENT *next;
};
struct STUDENT *createList(); // 创建链表
void outputLinkedList(struct STUDENT *head); // 遍历链表
void queryByScore(struct STUDENT *head, int s); // 成绩查询
void sysMenu(); // 系统菜单
int main()
{
struct STUDENT *head;
sysMenu();
head = createList();
outputLinkedList(head);
int s;
scanf("%d", &s);
queryByScore(head, s);
return 0;
}
struct STUDENT *createList() // 定义创建链表函数
{
struct STUDENT *head, *p, *q;
char name[20];
head = (struct STUDENT *)malloc(sizeof(struct STUDENT));
if (head == NULL) {
printf("内存分配失败\n");
exit(1);
}
head->next = NULL;
p = head;
while (1) {
printf("Please input student's name('none' means end of input): ");
scanf("%s", name);
if (strcmp(name, "none") == 0) {
break;
}
q = (struct STUDENT *)malloc(sizeof(struct STUDENT));
if (q == NULL) {
printf("内存分配失败\n");
exit(1);
}
strcpy(q->name, name);
printf("Please input %s's score: ", name);
scanf("%d", &(q->score));
p->next = q;
p = q;
}
p->next = NULL;
return head;
}
void outputLinkedList(struct STUDENT *head) // 定义遍历链表函数
{
struct STUDENT *p;
printf("\noutput links'node name and score:\n");
for (p = head->next; p != NULL; p = p->next)
{
printf("Name is %s, Score is %d\n", p->name, p->score);
}
}
void queryByScore(struct STUDENT *head, int s) // 定义成绩查询函数
{
struct STUDENT *p;
for (p = head->next; p != NULL; p = p->next)
{
if (p->score == s)
{
printf("%s\n", p->name);
return;
}
}
printf("not found\n");
}
void sysMenu() // 定义系统菜单函数
{
printf("====================\n");
printf(" link's operator\n");
printf(" 1. create Link\n");
printf(" 2. forEach Link\n");
printf(" 3. query score\n");
printf(" 4. insert node\n");
printf(" 5. delete node\n");
printf(" 0. exit\n");
printf("====================\n");
}
在queryByScore函数中,可以使用一个for循环遍历链表,找到第一个成绩与s相等的节点,然后输出该节点的姓名。如果循环结束后仍然没有找到匹配的节点,则输出"not found"。注意将查询函数放在循环遍历函数之后调用。