|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
为什么写入两个节点,第一个数据不见了
#include <stdio.h>
#include <stdlib.h>
struct Book
{
char title[128];
char author[40];
struct Book* next;
};
void printBook (struct Book* book)
{
do
{
printf("%s\n",book->title);
printf("%s\n",book->author);
book = book->next;
}
while(book->next!=NULL);
}
void getinput (struct Book** book)
{
struct Book* new_book,*temp;
new_book = (struct Book *)malloc(sizeof(struct Book));
scanf("%s%s",new_book->title,new_book->author);
if (*book == NULL)
{
*book = new_book;
new_book->next = NULL;
}
else
{
temp = *book;
*book = new_book;
new_book->next = temp;
}
}
void realse_book(struct Book* book)
{
struct Book * nextone;
do
{
nextone = book->next;
free(book);
book = nextone;
}
while(book->next!=NULL);
}
int main()
{
int ch = 1;
struct Book *book = NULL,*library = NULL;
while (1)
{
printf("请输入要插入的书名和作者");
getinput(&library);
printf("是否退出?(1/0)");
scanf("%d",&ch);
if (ch ==0)
{
break;
}
}
printBook(library);
return 0;
}
问题出在getinput函数中,当book不为空时,你将新节点插入到了链表的头部,但是并没有把原始的链表连接起来。所以只有第一个输入的数据能够正常输出,后续的数据都无法访问。
解决方法是,在将新节点插入到链表头部之后,需要把原始的链表连接到新节点的next上,使得链表保持完整。
以下是修改后的代码:
- #include <stdio.h>
- #include <stdlib.h>
- struct Book
- {
- char title[100];
- char author[100];
- struct Book* next;
- };
- void printBook(struct Book* book)
- {
- while (book != NULL) {
- printf("%s\n", book->title);
- printf("%s\n", book->author);
- book = book->next;
- }
- }
- void getinput(struct Book** book)
- {
- struct Book* new_book = (struct Book*)malloc(sizeof(struct Book));
- scanf("%s%s", new_book->title, new_book->author);
- new_book->next = *book; // 将原始链表连接到新节点的next上
- *book = new_book; // 更新链表头指针
- }
- void release_book(struct Book* book)
- {
- struct Book* nextone;
- while (book != NULL) {
- nextone = book->next;
- free(book);
- book = nextone;
- }
- }
- int main()
- {
- int ch = 1;
- struct Book* library = NULL;
- while (ch == 1) {
- printf("请输入要插入的书名和作者: ");
- getinput(&library);
- printf("是否退出?(1/0)");
- scanf("%d", &ch);
- }
- printBook(library);
- release_book(library);
- return 0;
- }
复制代码
这样,即使插入多个节点,也能够正确输出所有的数据。同时,使用完链表后记得释放内存。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
|
-
|