基于链式存储结构的图书信息表的最爱图书的查找C语言代码
时间: 2023-12-19 18:07:02 浏览: 160
以下是基于链式存储结构的图书信息表的最爱图书的查找C语言代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义图书信息结构体
typedef struct Book {
char id[10]; // 书号
char name[50]; // 书名
float price; // 价格
struct Book *next; // 指向下一个节点的指针
} Book;
// 创建图书信息链表
Book *createBookList(int n) {
Book *head, *p, *q;
head = (Book *)malloc(sizeof(Book));
head->next = NULL;
q = head;
for (int i = 0; i < n; i++) {
p = (Book *)malloc(sizeof(Book));
printf("请输入第%d本书的信息:\n", i + 1);
printf("书号:");
scanf("%s", p->id);
printf("书名:");
scanf("%s", p->name);
printf("价格:");
scanf("%f", &p->price);
q->next = p;
q = p;
}
q->next = NULL;
return head;
}
// 查找最爱的图书
Book *findFavoriteBook(Book *head, char *favoriteBookName) {
Book *p = head->next;
while (p != NULL) {
if (strcmp(p->name, favoriteBookName) == 0) {
return p;
}
p = p->next;
}
return NULL;
}
// 输出图书信息
void printBookInfo(Book *book) {
printf("书号:%s\n", book->id);
printf("书名:%s\n", book->name);
printf("价格:%.2f\n", book->price);
}
int main() {
int n;
char favoriteBookName[50];
Book *head, *favoriteBook;
printf("请输入图书数量:");
scanf("%d", &n);
head = createBookList(n);
printf("请输入最爱的图书名字:");
scanf("%s", favoriteBookName);
favoriteBook = findFavoriteBook(head, favoriteBookName);
if (favoriteBook != NULL) {
printf("您最爱的图书信息如下:\n");
printBookInfo(favoriteBook);
} else {
printf("抱歉,没有找到您最爱的图书。\n");
}
return 0;
}
```
阅读全文