|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 dutingyu 于 2020-11-6 01:28 编辑
看《带你学c带你飞》视频,学到链表把我绕晕了,希望大神帮我解解惑,我的问题在下面代码的注释里,不太明白*library的含义,谢谢大家了
- #include<stdio.h>
- #include<stdlib.h>
- struct Book {
- char title[128];
- char author[40];
- struct Book *next;
- };
- 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);//需要stdlib.h
- }
- getInput(book);
- if(*library!=NULL){ //那么*library不就是取值的意思吗?library取值不就是下一个节点地址上的值了吗。按照小甲鱼老师所讲,这里目的应该是修改头节点的内容呀
- temp=*library
- *library=book //还是说*library是指向指针的指针这个形参的书写形式啊
- book->next=temp;
- }
- else{
- *library=book;
- book->next=NULL;
- }
- }
-
- void printLibrary(struct Book *library){
- struct Book *book;
- int count = 1;
- book=library;
- while(book!=NULL){
- printf("-----------Book%d-----------\n",count);
- printf("书名:%s\n",book->title);
- printf("作者:%s\n",book->author);
- book=book->next;
- count++;
- }
- }
- void releseLibrary(struct Book *library){
- struct Book *temp;
- while(library!=NULL){
- temp=library->next;
- free(library);
- library=temp;
- }
- }
- int main(){
- struct Book *library=NULL;
- int ch;
- while(1){
- do{
- printf("是否录入书籍信息(Y/N):");
- ch=getchar();
- } while(ch!='Y'&&ch!='N');
- if(ch=='Y')
- {
- addBook(&library);
- }
- else
- {
- break ;
- }
- }
- do{
- printf("是否打印书籍信息(Y/N):");
- ch=getchar();
- } while(ch!='Y'&&ch!='N');
- if(ch=='Y')
- {
- printLibrary(library);
- }
- releseLibrary(library);
- return 0;
- }
复制代码 |
|