有一链式结构,定义如下 : struct stu{ char name[20]; int no; struct stu *next; }; 创建一个函数myindex(head,name),在链表head中查找name域为name的结点,返回查找后结果。如果p链表中结点的name域与name相同,返回该结点的地址,如果没找到,返回NULL。 程序中create函数已经为我们创建了一个有10个结点的无头结点的链表。 函数接口定义: 在这里描述函数接口。例如: struct stu * myindex(struct stu *head,char *name); 在这里解释接口参数。例如:其中 head 和 name 都是用户传入的参数。 head 是链表的头指针; name 是要查找的姓名字符串。函数的返回值为如果p链表中结点的name域与name相同,返回该结点的地址,如果没找到,返回NULL。
时间: 2023-06-04 17:02:51 浏览: 163
struct stu * myindex(struct stu *head,char *name);
参数说明:
head:链表的头指针;
name:要查找的姓名字符串。
返回值:
如果p链表中结点的name域与name相同,返回该结点的地址,如果没找到,返回NULL。
函数实现:
struct stu * myindex(struct stu *head, char *name){
struct stu *p = head->next;
while(p != NULL){
if(strcmp(p->name, name) == 0){
return p;
}
p = p->next;
}
return NULL;
}
在这个函数中,我们使用了指针p来遍历整个链表,查找是否存在与name相同的结点。如果找到了,我们就返回该结点的地址,否则返回NULL。
相关问题
有一链式结构,定义如下 : struct stu{ char name[20]; int no; struct stu *next;
这是一个链式结构体,其中包含了三个成员:name、no 和 next。其中,name 是一个长度为 20 的 char 数组,用来存储学生姓名;no 是一个整型变量,用来存储学号;next 是一个指向下一个结构体的指针,用来构建链表。
这个链式结构体可以用来表示一个学生信息,每个结构体代表一个学生,通过 next 指针可以将多个学生信息串联起来形成一个链表。在链表中,每个结构体代表一个节点,next 指针指向下一个节点,最后一个节点的 next 指针为 NULL,表示链表的末尾。
有一链式结构,定义如下 : struct stu{ char name[20]; int no; struct stu *next; }; 创建一个函数create(),实现无头结点的链表,有m个结点,函数的返回值为链表的头指针。
好的,我来给你写一个实现 create() 函数的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct stu{
char name[20];
int no;
struct stu *next;
};
struct stu* create(int m){
struct stu *head, *p, *q;
int i;
head = NULL;
for(i=0; i<m; i++){
p = (struct stu*)malloc(sizeof(struct stu));
printf("请输入第%d个学生的姓名和学号:", i+1);
scanf("%s %d", p->name, &p->no);
p->next = NULL;
if(head == NULL){
head = p;
}else{
q->next = p;
}
q = p;
}
return head;
}
int main(){
int m;
struct stu *p;
printf("请输入学生的个数:");
scanf("%d", &m);
p = create(m);
printf("学生的信息如下:\n");
while(p != NULL){
printf("%s %d\n", p->name, p->no);
p = p->next;
}
return 0;
}
```
这是一个基本的链表创建函数,通过循环输入学生的姓名和学号,然后将其加入链表的尾部,最后返回链表的头指针。在主函数中,我们可以使用返回的头指针遍历整个链表并输出每个学生的信息。注意:这里的链表是无头结点的,头指针就是链表的第一个结点的指针。