【发布时间】:2018-12-03 15:10:55
【问题描述】:
我正在尝试编写一段将元素添加到列表的代码。
typedef struct things {
int value;
struct things *next;
} something;
int main()
{
int input = 0;
something *head = NULL;
something *current = NULL;
current = head; //current points to head address
while(input != -1)
{
scanf("%d", &input);
while(current != NULL) //loop until current node returns NULL
{
current = current->next; //go to next node
}
current = malloc(sizeof(something)); //allocate memory for new node assuming current is NULL
current->value = input;
current->next = NULL; //next points to NULL
}
current=head; //current points back to head
while(current != NULL)
{
printf("%d -> ", current->value);
current = current->next;
}
puts("NULL");
return 0;
}
但是,当我尝试通过列表打印时,我没有得到任何输出。所以即使我输入 1 2 3 4..etc 打印功能也不会输出任何东西
while(current != NULL)
{
printf("%d -> ", current->value);
current = current->next;
}
puts("NULL");
我期待像 1 -> 2 -> 3 -> ... 9 -> NULL 这样的输出。我刚刚开始学习链表,因此不胜感激。
【问题讨论】:
-
current = malloc(sizeof(something));你永远不会将这个新节点连接到列表的末尾,或者即使它是第一个节点,也要设置头指针。 -
您在 malloc 之前的循环是浪费时间,因为您所做的只是将 current 重新分配给 malloc 的返回。你真正需要的是一个指向指针的指针,然后你返回 'next' 的地址并用 *current 赋值
标签: c printf singly-linked-list