求大神利用C语言链表写一个 通过学生姓名可以查找学生寝室和学号 通过学生学号可以查找学生寝室

2025-06-20 09:57:48
推荐回答(4个)
回答1:

1 思路

创建链表,主要是使用malloc函数

比较姓名,使用strcmp

2 代码

#include
#include
#include
/*控制台输入数据如下
101 王二 501
102 赵四 502
103 张三 523
*/
typedef struct _Stduent{
int id_stu;
int id_dormioty;
char name[20];
struct _Stduent *next;
} Student;

Student *init(){
puts("***输入信息:形如\"学号 姓名 寝室号\"(按两次回车结束)");
int Size = sizeof(Student);
Student *head = NULL, *p1, *p2;
int n = 0;
char buffer[64];
while (true){
gets(buffer);
if (buffer[0] == '\0'){
    if(n>0)
p2->next = NULL;
    break;
}
if (n++ == 0)
head = p1 = p2 = (Student*)malloc(Size);
else
p2 = (Student*)malloc(Size);
sscanf(buffer, "%d %s %d", &p2->id_stu, &p2->name, &p2->id_dormioty);
p1->next = p2;
p1 = p2;
}
return head;
}
void search_by_name(Student*p){
char name[20];
printf("输入姓名:");
getchar();
gets(name);
while (p != NULL){
if (strcmp(p->name, name) == 0){
printf("姓名为%s的学生:寝室号为%d,学号为%d\n", p->name, p->id_dormioty, p->id_stu);
return;
}
p = p->next;
}
printf("真遗憾...,未找到姓名为%s的学生\n", name);
}
void search_by_id_stu(Student*p){
int id_stu;
printf("输入学号:");
scanf("%d", &id_stu);
while (p != NULL){
if (id_stu == p->id_stu){
printf("学号为%d的学生:寝室号为%d,姓名为%s\n", p->id_stu, p->id_dormioty, p->name);
return;
}
p = p->next;
}
printf("真遗憾...,未找到学号为%d的学生\n", id_stu);
}
int main(){
Student *p = init();
int n;
do{
printf("\n***选择操作:1.通过姓名查找;2.通过学号查找;3.退出.\n请输入:");
scanf("%d", &n);
switch (n){
case 1:
search_by_name(p);
break;
case 2:
search_by_id_stu(p);
break;
}
} while (n != 3);

Student*p1 = p;
while (p1 != NULL){
p1 = p1->next;
free(p);
p = p1;
}
return 0;
}

3 运行效果

回答2:

这个很好写的,通过头指针轮询就行了,这种查找说白了就是比较么。

回答3:

去淘宝买一个吧!

回答4:

给不给money?