有一链式结构,定义如下 : struct stu{ char name[20]; int no; struct stu *next; }; 创建一个函数myindex(head,name),在链表head中查找name域为name的结点,返回查找后结果。如果p链表中结点的name域与name相同,返回该结点的地址,如果没找到,返回NULL。 程序中create函数已经为我们创建了一个有10个结点的无头结点的链表。
时间: 2024-03-16 19:47:41 浏览: 22
好的,下面是实现myindex函数的代码:
```
struct stu *myindex(struct stu *head, char *name) {
struct stu *p = head;
while (p != NULL) {
if (strcmp(p->name, name) == 0) {
return p;
}
p = p->next;
}
return NULL;
}
```
在主函数中调用该函数,可以这样写:
```
int main() {
struct stu *head = create();
char name[20];
printf("请输入要查找的姓名:");
scanf("%s", name);
struct stu *p = myindex(head, name);
if (p != NULL) {
printf("找到了,该学生的学号是%d\n", p->no);
} else {
printf("没找到\n");
}
return 0;
}
```
其中,create函数可以参考如下代码:
```
struct stu *create() {
struct stu *head = NULL, *p = NULL, *tail = NULL;
int n = 10;
for (int i = 0; i < n; 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 {
tail->next = p;
}
tail = p;
}
return head;
}
```
注意,create函数中没有创建头结点,而是创建了一个指向第一个节点的指针head。