初学单链条

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

#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; 
}
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页