我使用一个函数将新节点插入到我的单链表中,但是当我在插入后打印出节点内的所有值时,我只得到第一个节点的值:
// 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地址。
如果您返回头指针并正确更新它,它可能会解决您的问题。
关于c:使用函数将新节点插入到单链表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46994029/