| 
 | 
 
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册  
 
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,*temp;                //这里的book指针是头结点吗?  
         
        book = (struct Book*)malloc(sizeof(struct Book)); 
        if(book == NULL) 
        { 
                printf("内存分配失败了\n"); 
                exit(1); 
        } 
        getInchar(book); 
        if(*library!=NULL)                        //为什么要把library的值赋给book->next, 
        {                                                // next不应该指向下一个struct Book类型的结构体吗?  
                temp = *library; 
                *library = book; 
                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: ",count); 
                printf("书名:%s",book->title); 
                book = book->next; 
                count++; 
        } 
} 
 
void  releaseLibrary(struct Book *library) 
{ 
        while(library != NULL) 
        { 
                library = library->next; 
                free(library); 
        } 
} 
 
int main(void) 
{ 
        struct Book *library = NULL;         //这个library是元首结点吗? 那么头指针在哪啊?  
        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; 
}
 本帖最后由 一叶枫残 于 2021-2-15 17:46 编辑  
 
你这个程序是没有头结点的(图片建议与代码一起食用,例如左边放图右边放代码一起看) 
 
 
 |   
 
 
 
 |