链表问题
本帖最后由 我叫MD 于 2019-4-6 19:47 编辑本人今天刚刚学到小甲鱼课程的第45讲(链表1)
下面是小甲鱼的代码(代码比较多,还望多多见谅),运行没问题
#include <stdio.h>
#include <stdlib.h>
//定义一个结构体 (单链表的声明)
struct Book
{
char title;
char author;
struct Book *next;
};
//录入信息(填充书名)
void getInput(struct Book *book)
{
printf("请输入书名:");
scanf("%s",book->title);
printf("请输入作者:");
scanf("%s",book->author);
}
void addBook(struct Book **library)
{
struct Book *book,*temp;
book = (struct Book*)malloc(sizeof(struct Book));
if(book == NULL)
{
printf("内存空间分配失败\n");
exit(1);
}
getInput(book);
if(*library != NULL)
{
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("第%d本书\n",count);
printf("书名:%s\n",book->title );
printf("作者:%s\n",book->author );
book = book->next;
count++;
}
}
//释放addBook函数中结构体指针(book)申请的内存空间
void releaselibrary(struct Book *library)
{
struct Book *temp;
while(library != NULL)
{
temp = library;
library = library->next;
free(temp);
}
}
int main()
{
struct Book *library = NULL;
//录入3本书的信息
for(int i = 1; i <= 3; i++)
{
addBook(&library);
}
printlibrary(library);
releaselibrary(library);
return 0;
}
然后是我的代码
我的代码是把addBook函数的参数修改了一下,由
void addBook(struct Book **library)
这样变成了
void addBook(struct Book *library)
然后下面由
if(*library != NULL)
{
temp = *library;
*library = book;
book->next = temp;
}
else
{
*library = book;
book->next = NULL;
}
这样变成了
if(library != NULL)
{
temp = library;
library = book;
book->next = temp;
}
else
{
library = book;
book->next = NULL;
}
然后main函数中传入对应的参数,其他完全一样,我写的这个就不打印,希望大神给解释一下 本帖最后由 jackz007 于 2019-4-6 20:10 编辑
原程序传入参数是指向指针的指针,意图是有可能修改这个值
void addBook(struct Book **library)
. . . . . .
*library = book ; // 修改指针 library 指向地址的内容,其实就是修改 main() 中的指针 library 的值。
. . . . . .
int main()
. . . . . .
addBook(&library);// 以指针 library 的地址为参数调用函数意图是有可能在函数中修改指针 library 的值
楼主修改成指针,使这种可能不再存在。
void addBook(struct Book *library)
. . . . . .
library = book;// 修改指针 library 本身的值,不会把影响传递回 main() 函数。
页:
[1]