初学单链条

学完单链条头发又掉了几根
用单链条做一个图书管理系统

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct Book 
{
		char title[128];
		char author[40];
		struct Book *next;
};
void getInput(struct Book *);
void addBook(struct Book **);
void printLibrary(struct Book *);
struct Book *selectBook(struct Book *,char *);
void printBook(struct Book *);
void releaseLibrary(struct Book **);


void getInput(struct Book *book)
{
		printf("请输入图书的名称:");
		scanf("%s",book->title);
		printf("请输入图书的作者:");
		scanf("%s",book->author);
}
void addBook(struct Book **library)
{
		struct Book *book;
		static struct Book *tail;//创建一个指针永远指向library最后一本书 
		book = (struct Book *)malloc(sizeof(struct Book));
		getInput(book);
		if (*library != NULL)//检查library是否是空的   使用尾插法 
		{
				tail->next = book;
				book->next = NULL;
		}
		else
		{
				*library = book;
				book->next = NULL;
		}
		tail = book; 
}
void printLibrary(struct Book *library)
{
		struct Book *book;
		book = library;
		while (book != NULL)
		{
				printf("书名:%s\n",book->title);
				printf("作者:%s\n",book->author);
				book = book->next;
		}
		printf("\n      At the bottom      \n");
}
struct Book *selectBook(struct Book *library,char *target)
{
		struct Book *book;
		book = library;
		while (book != NULL)
		{
				if (!strcmp(book->title,target) || !strcmp(book->author,target))//用户可以随便输入书名或者作者名来检索 
				{
						break;
				}
				book = book->next; 
		}
		return book;
}
void printBook(struct Book *book)//打印检索的图书 
{
		printf("书名:%s\n",book->title);
		printf("作者:%s\n",book->author);
}
void releaseLibrary(struct Book **library)//释放动态申请的内存 
{
		struct Book *temp;
		if (*library != NULL)
		{
				temp = (*library)->next;
				free(*library);
				*library = temp;
		}
}
int main(void)
{
		struct Book *library = NULL;
		char ch;
		char target[33];
		while (1)//录入数据部分 
		{
				printf("请问您是否要录入数据(Y/N):");
				do
				{
						ch = getchar();
				}while(ch != 'Y' && ch != 'N');
				if (ch == 'Y')
				{
						addBook(&library);
				}
				else
				{
						break;
				}
		}
		printf("下面是图书库内容\n====================\n");
		printLibrary(library);//打印图书库部分 
		while (1)//查找书籍部分
		{
				printf("请问你是否要检索书籍(Y/N):");
				do
				{
						ch = getchar();
				}while(ch != 'Y' && ch != 'N');
				if (ch == 'Y')
				{
						struct Book *book; 
						printf("请输入该书的相关信息:");
						scanf("%s",target);
						book = selectBook(library,target);
						if (book == NULL)
						{
								printf("\n很抱歉,图书库检索不到这本书\n");
						}
						else
						{
								do//防止同名作者的情况 
								{
										printf("已找到目标书籍:\n");
										printBook(book);
								}while ((book = selectBook(book->next,target)) != NULL); 
								
						}
				}
				else
				{
						break;
				}
		 }
		 releaseLibrary(&library);
		 printf("感谢您对我们的支持\n");
		 return 0; 
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值