|
发表于 2022-6-18 01:41:37
|
显示全部楼层
本帖最后由 桃花飞舞 于 2022-6-18 01:49 编辑
感觉二级指针比较复杂,但是又没想到好的方法,不过像这个如果不用每次都询问要不要输入而用固定输入的个数倒是可以不用二级指针来做。
我觉得下面的方法思路更清晰不至于太难理解。其实就是链表的创建和遍历。
看我代码吧
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
struct BOOK
{
char title[30]; //数据域 书名
char author[30]; //数据域 作者
struct BOOK *next; //指针域 (指向下一BOOK)
};
void getinput(struct BOOK *book) //获取输入
{
printf("请输入书名: ");
scanf("%s", book->title);
printf("请输入作者: ");
scanf("%s", book->author);
}
struct BOOK* addBook()
{
//1.需要三个指针
//2.节点的链接
struct BOOK *head = NULL;
struct BOOK *last = NULL;
struct BOOK *pNew = NULL;
int n;
int i;
printf("请输入要录入信息的个数:\n");
scanf("%d",&n);
for(i=0;i<n; i++)
{
pNew = (struct BOOK *)malloc(sizeof(struct BOOK));
printf("请输入第%d本书的书名和作者: ",i+1);
scanf("%s %s",pNew->title,pNew->author);
if(i == 0)
{
head = last = pNew;
}
else
{
last->next = pNew;
last = pNew;
}
last->next = NULL;
}
return head;
}
void print(struct BOOK *book) //打印链表每个BOOK的信息(与添加的顺序相反) 遍历
{
//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 freelibrary(struct BOOK *library) //这个函数有问题,已经修改过了
{
struct BOOK *temp;
while (library != NULL)
{
temp = library->next;
free(library);
// library = library->next; //问题就在这,上面library已经被free了怎么还能访问library->next呢
library = temp;
}
}
int main(void)
{
printf("\n汉字\n");
struct BOOK *library = NULL; //链表头指针,它里面保存的是第一个Book的地址
library = addBook();
print(library);
return 0;
}
|
评分
-
查看全部评分
|