|
发表于 2021-8-25 09:31:01
|
显示全部楼层
- #include<stdio.h>
- #include<stdlib.h>
- //#include<malloc.h>
- struct library
- {
- char bookname[500];
- char author[500];
- struct library* next;
- };
- void addbook(struct library** first);
- void printbook(struct library* first);
- void releasespace(struct library** first);
- int main()
- {
- struct library* first = NULL;
- first = (struct library*)malloc(sizeof(struct library)); //在这里初始化就好了
- int ch;
- printf("1添加图书\n");
- printf("2打印图书\n");
- printf("3退出\n");
-
- while (1)
- {
-
- do
- { printf("输入选项");
- scanf("%d", &ch);
- switch(ch)
- {case 1:
- addbook(&first);
- break;
- case 2:
- printbook(first);
- break;}
- } while (ch !=3);
- }
- releasespace(&first);
- return 0;
- }
- void addbook(struct library** first)
- {
- struct library* book, * temp;
- book = (struct library*)malloc(sizeof(struct library));
- // *first = (struct library*)malloc(sizeof(struct library)); 每次进来都你都分配空间,相当于声明一个新变量
- printf("请输入需要添加图书的名字:");
- scanf("%s", book->bookname);
- printf("请输入图书作者:");
- scanf("%s", book->author);
- book->next=(*first)->next;
- (*first)->next=book;
- }
- void printbook(struct library* first)
- {
- struct library* book;
- book = first->next; //头指针是空节点,要指向下一个
- while (book != NULL)
- {
- printf("书的名字:%s", book->bookname);
- printf("书的作者:%s", book->author);
- book = book->next;
- }
- }
- void releasespace(struct library** first)
- {
- struct library* temp;
- while (*first != NULL)
- {
- temp = *first;
- *first = (*first)->next;
- free(temp);
- }
- }
复制代码 |
|