@RE~ 2022-05-08 15:05 采纳率: 0%
浏览 15
已结题

不理解addBook部分的代码,为什么没增加到**library中却可以打印出来?




//视频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;
}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    问题事件

    • 系统已结题 5月16日
    • 创建了问题 5月8日

    悬赏问题

    • ¥15 Opencv(C++)异常
    • ¥15 VScode上配置C语言环境
    • ¥15 汇编语言没有主程序吗?
    • ¥15 这个函数为什么会爆内存
    • ¥15 无法装系统,grub成了顽固拦路虎
    • ¥15 springboot aop 应用启动异常
    • ¥15 matlab有关债券凸性久期的代码
    • ¥15 lvgl v8.2定时器提前到来
    • ¥15 qtcp 发送数据时偶尔会遇到发送数据失败?用的MSVC编译器(标签-qt|关键词-tcp)
    • ¥15 cam_lidar_calibration报错