|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
我把小甲鱼的代码按我的理解改了一下,运行结果相同,学长瞄下我理解是否有误
这是我的代码
#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)
{
struct Book *book, *temp;
book = (struct Book *)malloc(sizeof(struct Book));
if(book == NULL)
{
printf("内存分配失败");
exit(1);
}
getinput(book);
if(*library != NULL)
{
book -> next = *library; //直接把头指针指的地址给新节点
*library = book; //新节点的地址给头指针
}
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 releaselibrary(struct Book *library)
{
struct Book *temp;
while(library != NULL)
{
temp = library;
library = library -> next;
free(temp);
}
}
int main()
{
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;
}
这是小甲鱼的代码
#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)
{
struct Book *book, *temp;
book = (struct Book *)malloc(sizeof(struct Book));
if(book == NULL)
{
printf("内存分配失败");
exit(1);
}
getinput(book);
if(*library != NULL)
{
temp = *library; //temp 中间变量保存头指针
*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:\n", count);
printf("书名:%s\n", 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()
{
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;
}
本帖最后由 jhq999 于 2022-4-21 08:52 编辑
头插法下面那个没必要有中间值,中间值一般用于互换
比如:
- tmp=p;
- p=p->next;
- tmp->next=p->next;
- p->next=tmp;
复制代码
|
-
-
|