【发布时间】:2022-01-21 03:55:28
【问题描述】:
我已经尝试了很多次来设置我的头指针指向第一个节点。首先(在空列表中)它正确地指向第一个节点。但是在第一个循环之后,头指针指向链接的新节点。其实现在我也很不确定我的整个代码。
int main(void){
struct library *head = NULL; //set the head pointer to NULL
int option;
printf("Enter the number:");
while((option = getchar())!= 9){
switch(option){
case '1':
{
char title[1000];
char author[1000];
char subject[1000];
printf("Enter title of the book you want to add:");
scanf("%s",title);
printf("Enter author of the book you want to add:");
scanf("%s",author);
printf("Enter subject of the book you want to add:");
scanf("%s",subject);
add_book(title,author,subject,&head);
printf("successful! and head pointer is pointing to %s\n",head->collection.title);
break;
}
}
}
void add_book(char title[],char author[],char subject[], struct library ** head){
struct library *current;
struct library *newnode = malloc(sizeof(struct library));
newnode->collection.title = title;
newnode->collection.author = author;
newnode->collection.subject = subject; // assigning value inside newnode
newnode->num_books = 0;
newnode->next = NULL; // assign NULL value to the end of newnod
//when the head is NULL which means when the list is empty
if(*head == NULL)
{
current = newnode;
*head = current;
return;
}
else
{
current = *head; //assign the first node to current pointer
//find the last node of the list
while(current->next != NULL)
{
current = current->next;
}
current->next = newnode; // link the last node to new node
return;
}
}
这是这个结构
struct book {
char* title;
char* author;
char* subject;
};
struct library {
struct book collection;
int num_books;
struct library* next;
};
【问题讨论】:
-
为你的结构推荐 typedef,让阅读更容易 ex.) typedef struct library library
-
= strdup(title)等。您的本地 char 数组将无法返回。 -
您的
main函数缺少右大括号 (})。请注意发布您的Minimal, Reproducible Example 的准确副本 - 最好带有适当的缩进。
标签: c linked-list