C语言单链表 看不懂temp->next = book; book->next =NULL;



//视频45:单链表

/*
    struct Test
    {
		int x;
		int y;
		struct Test *test;//指向自身的结构;
	};
*/

/*
单链表:信息域指针域->

*/


#include<stdlib.h>
#include<stdio.h>

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值