//视频45:单链表
/*
struct Test
{
int x;
int y;
struct Test *test;//指向自身的结构;
};
*/
/*
单链表:信息域指针域->
*/
#include
#include
struct Book
{
char title[128];//书名
char author[40];//作者
struct Book *next;
//到此完成单链表节点的声明
//插入节点 头插法
};
//void getInput(struct Book *book);
//void addBook(struct Book **library);
//void printLibrary(struct Book *library);
//void releaseLibrary(struct Book **library);
//输入书籍信息
void getInput(struct Book *book)
{ //传入一个结构体指针
printf("请输入书名:");
scanf("%s",book->title);
printf("请输入作者:");
scanf("%s",book->author);
}
//增加书籍
void addBook(struct Book **library)
{ //修改library进行两层解引用
struct Book *book, *temp;
book = (struct Book *)malloc(sizeof(struct Book));
//在堆里面申请一个新的节点
if(book == NULL)
{
printf("内存分配失败了!\n");
exit(1);
}
//调用getInput填充内容
getInput(book);//传进book的地址
if(*library != NULL)
{
temp =*library;
//定位单链表的尾部位置
while( temp->next !=NULL )
{
temp = temp->next;
}
//插入数据
temp->next = book;
book->next =NULL;
}else{
*library = book;
//head执行book节点
book->next = NULL;
//book指向NULL
}
}
//打印书籍
void printLibrary(struct Book *library)
{
struct Book *book;
int count =1;
book = library;
while(book !=NULL)
{
printf("Book%d:",count);
printf("书名:%s\t\t",book->title);
printf("作者:%s\n",book->author);
book= book->next;
count++;
}
}
//释放
void releaseLibrary(struct Book **library)
{
struct Book *temp;
while( *library !=NULL )
{
temp = *library;
*library = (*library)->next;
free(temp);
}
}
int main(void)
{
struct Book *library = NULL;
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);
}
releaseLibrary(&library);
return 0;
}
看不懂addBook最后部分,没有将新增的书籍存ru**library中,为什么还可以打印出来?
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)