|
发表于 2024-5-17 16:41:18
|
显示全部楼层
//不使用指针的指针demo(样例),未加释放内存函数
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Book {
char title[128];
char author[40];
struct Book *next;
};
void addBook(struct Book *plibrary);
void getBook(struct Book *newBook);
void printLibrary(struct Book *plibrary);
struct Book *searchBook(struct Book *plibrary, char *target);
void printBook(struct Book *pbook);
void getBook(struct Book *newBook) {
newBook->next = NULL;
printf("请输入书籍的名称:");
scanf("%s", newBook->title);
printf("请输入书籍的作者:");
scanf("%s", newBook->author);
}
void addBook(struct Book *plibrary) {
static struct Book *temp;
struct Book *newBook;
newBook = (struct Book *)malloc(sizeof(struct Book));
if (newBook == NULL) {
printf("内存分配失败了");
exit(1);
} else {
getBook(newBook);
if (plibrary->next != NULL) {
temp->next = newBook;
} else {
plibrary->next = newBook;
}
temp = newBook;
}
}
void printLibrary(struct Book *plibrary) {
struct Book *link;
link = plibrary;
int count = 1;
while (link->next != NULL) {
link = link->next;
printf("第%d本书籍信息\n", count);
printf("%s\n", link->title);
printf("%s\n", link->author);
count++;
}
}
struct Book *searchBook(struct Book *plibrary, char *target) {
struct Book *book;
book = plibrary->next;
while (book != NULL) {
if (!strcmp(book->title, target) || !strcmp(book->author, target)) {
break;
}
book = book->next;
}
return book;
}
void printBook(struct Book *pbook) {
printf("书名:%s\n", pbook->title);
printf("作者:%s\n", pbook->author);
}
int main() {
static struct Book library;
library.next = NULL;
struct Book *book;
char target[128];
int ch;
while (1) {
printf("请问是否需要录入书籍:(y/n)");
do {
ch = getchar();
} while (ch != 'y' && ch != 'n');
if (ch == 'y') {
addBook(&library);
} else {
break;
}
}
printf("请问是否需要打印书籍信息(y/n)");
do {
ch = getchar();
} while (ch != 'y' && ch != 'n');
if (ch == 'y') {
printLibrary(&library);
}
while (1) {
printf("请问是否需要查找书籍:(y/n)");
do {
ch = getchar();
} while (ch != 'y' && ch != 'n');
if (ch == 'y') {
printf("请输入您要查找的书籍名称或者作者姓名:");
scanf("%s", target);
book = searchBook(&library, target);
if (book == NULL) {
printf("很抱歉,没有找到符合条件的书籍...\n");
} else {
do {
printf("已找到符合条件的书籍:\n");
printBook(book);
} while ((book = searchBook(book, target)) != NULL);
}
} else {
break;
}
}
return 0;
}
|
|