马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 BaysideLizard 于 2023-11-29 23:00 编辑 #include <stdio.h>
#include <stdlib.h>
//鱼C论坛——BaysideLizard写于2023年11月29日
struct Book
{
char title[128];
char author[40];
struct Book *next;
//申请一个单链表节点
};
void addBook(struct Book **headLibrary);
void inputBook(struct Book *book);
void printLibrary(struct Book *headLibrary);
void releaseLibrary(struct Book **headLibrary);
int main()
{
struct Book *headLibrary = NULL;
char ch = 'l';
while(1)
{
printf("请问是否需要录入书籍信息[Y/n]:");
do
{
ch = getchar();
if(ch != '\n')
{
getchar();
}
}while(ch!='Y'&&ch!='N'&&ch!='y'&&ch!='n'&&ch!='\n');
if(ch == 'y' || ch == 'Y' || ch == '\n')
{
addBook(&headLibrary);
}
else
{
break;
}
}
while(1)
{
printf("请问是否需要输出书籍信息[Y/n]:");
do
{
ch = getchar();
if(ch != '\n')
{
getchar();
}
}while(ch!='Y'&&ch!='N'&&ch!='y'&&ch!='n'&&ch!='\n');
if(ch == 'y' || ch == 'Y' || ch == '\n')
{
printLibrary(headLibrary);
break;
}
else
{
break;
}
}
releaseLibrary(&headLibrary);
return 0;
}
//插入一个单链表节点(头插法)
void addBook(struct Book **headLibrary)
{
struct Book *book,*temp;
book = (struct Book *)malloc(sizeof(struct Book));
if(book == NULL)
{
printf("Memory allocation failed :(");
exit(1);
}
inputBook(book);
if(*headLibrary != NULL)
{
temp = *headLibrary;
*headLibrary = book;
book->next = temp;
}
else
{
*headLibrary = book;
book->next = NULL;
}
}
void inputBook(struct Book *book)
{
printf("请输入书名:");
scanf("%s",book->title);
getchar();
printf("请输入作者:");
scanf("%s",book->author);
getchar();
}
void printLibrary(struct Book *headLibrary)
{
struct Book *book;
int count = 1;
book = headLibrary;
while(book != NULL)
{
printf("Book%d:\n",count);
printf("书名:%s\n",book->title);
printf("作者:%s\n",book->author);
book = book->next;
++count;
}
}
//依次释放单链表节点
void releaseLibrary(struct Book **headLibrary)
{
struct Book *temp;
while(*headLibrary != NULL)
{
temp = *headLibrary;
*headLibrary = (*headLibrary)->next;
free(temp);
}
}
运行结果:
请问是否需要录入书籍信息[Y/n]:y
请输入书名:《零基础入门学习Python》
请输入作者:小甲鱼
请问是否需要录入书籍信息[Y/n]:
请输入书名:《带你学C带你飞》
请输入作者:小甲鱼
请问是否需要录入书籍信息[Y/n]:n
请问是否需要输出书籍信息[Y/n]:y
Book1:
书名:《带你学C带你飞》
作者:小甲鱼
Book2:
书名:《零基础入门学习Python》
作者:小甲鱼
Process returned 0 (0x0) execution time : 33.738 s
Press any key to continue.
在FishC学C的第24天 |