|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
今天学尾插法,跟着小甲鱼打程序,我完完全全按照他的程序写下来,可是他的程序可以正常运行,我就不可以,为毛啊?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Book //链表的结点
{
char title[20]; //信息域
struct Book *next; //指针域
} ;
void getInchar(struct Book *book) //录入书本信息的函数
{
printf("请输入书名:");
scanf("%s",book->title);
}
void addBook(struct Book **library)
{
struct Book *book;
static struct Book *tail;
book = (struct Book*)malloc(sizeof(struct Book));
if(book == NULL)
{
printf("内存分配失败了\n");
exit(1);
}
getInchar(book);
if((*library) != NULL)
{
//插入数据
tail->next = book;
book->next = NULL;
}
else
{
*library = book;
book->next = NULL;
}
tail = book;
}
void printLibrary(struct Book *library) //打印书籍信息的函数
{
struct Book *book;
int count = 1;
book = library;
while (book!=NULL)
{
printf("Book%d: ",count);
printf("书名:%s\n",book->title);
book = book->next;
count++;
}
}
struct Book *sousuo (struct Book *library,char *sou) //搜索书籍的函数
{
struct Book *book;
book = library;
while(book != NULL)
{
if(!strcmp(book->title,sou))
{
break;
}
book = book->next;
}
return book;
}
void printfBook(struct Book *sousuo) //打印搜索结果的函数
{
printf("书名:%s",sousuo->title);
}
void releaseLibrary(struct Book **library)
{
while(library != NULL)
{
struct Book *temp;
temp = *library;
*library = (*library)->next;
free(temp);
}
}
int main(void)
{
struct Book *library = NULL,*book; //头指针
int ch;
char *sou;
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);
}
printf("请输入搜索信息:");
scanf("%s",sou);
book = sousuo(library,sou);
if(book == NULL)
{
printf("\n很抱歉,没找到...");
}
else
{
do
{
printf("已找到符合条件的书籍。。。\n");
printfBook(book);
}while((book = sousuo(library->next,sou)) != NULL);
}
releaseLibrary(&library);
return 0;
} |
|