我使用了一个函数将新节点插入到我的单向链表中,但是当我在插入后打印出节点内的所有值时,我只得到第一个节点的值:
// Make list
createList(head, 17);
// Insert to list
for (int x = 9; x > 0; x /= 3)
{
if (!insertToList(head, x))
{
fprintf(stderr, "%s", error);
return 1;
}
}
该函数:
bool insertToList(NODE *head, int value)
{
NODE *node = malloc(sizeof(NODE));
if (node == NULL)
return false;
node -> number = value;
node -> next = head;
head = node;
return true;
}
-- 输出: 17
当我不使用函数时,一切都按预期工作:
// Make list
createList(head, 17);
// Insert to list
for (int x = 9; x > 0; x /= 3)
{
NODE *node = malloc(sizeof(NODE));
if (node == NULL)
{
fprintf(stderr, "%s", error);
return 1;
}
node -> number = x;
node -> next = head;
head = node;
}
-- 输出: 1 3 9 17
为什么?
你在函数中传递指针,更新它而不是返回它,在这种情况下,外部函数永远无法知道头部是否发生了变化。您还必须在 for 循环中适当地更新头部。
在不使用函数的情况下,每次插入时,for 循环都知道正确的 head 地址。
可能如果您返回头部指针并正确更新它,它应该可以解决您的问题。