|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 zz2329017 于 2020-2-13 14:20 编辑
if(*library != NULL)
{
temp = *library;
*library = book;
book->next = temp;
}
else
{
*library = book;
book->next = NULL;
}
和
if(*library = NULL)
{
*library = book;
book->next = NULL;
}
else
{
temp = *library;
*library = book;
book->next = temp;
}
有区别吗,为什么在同一段代码中结果不一样。
完整代码如下:
#include<stdio.h>
#include<stdlib.h>
struct Date
{
int year;
int month;
int day;
};
struct Book
{
char name[256];
char author[20];
float price;
struct Date date;
struct Book *next;
};
void getinput(struct Book *book);
void addbook(struct Book **library);
void print(struct Book *library);
void releaselibrary(struct Book *library);
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;
}//注 这个if不能反过来写!!!啊!!!!
}
void getinput(struct Book *book)
{
printf("请输入书名:");
scanf("%s",book->name);
printf("请输入作者:");
scanf("%s",book->author);
printf("请输入日期:");
scanf("%d%d%d",&book->date.year,&book->date.month,&book->date.day);
printf("请输入价格:");
scanf("%f",&book->price);
}
void print(struct Book *library)
{
struct Book *book;
int count = 1;
book = library;
while(book != NULL)
{
printf("Book%d:\n",count);
printf("书名:%s\n",book->name);
printf("作者:%s\n",book->author);
printf("日期:%d.%d.%d\n",book->date.year,book->date.month,book->date.day);
printf("价格:%.2f\n",book->price);
book = book->next;
count++;
}
}
void release(struct Book *library)
{
struct Book *book;
int count = 1;
book = library;
while(book!=NULL)
{
free(book);
book = book->next;
}
}
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("\n\n");
printf("是否需要打印所录入的书?(Y/N)");
do
{
ch = getchar();
}while(ch != 'Y' && ch != 'N');
if(ch=='Y')
{
print(library);
}
release(library);
return 0;
}
就不能认真一点吗?
|
|