c:使用函数将新节点插入到一个单链表中
问题描述:
我使用了一个函数来将新节点插入到我的单链表中,但是当我插入后打印出节点内的所有值时,我只能得到第一节点:c:使用函数将新节点插入到一个单链表中
// 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
当我不使用的功能,everythi NG按预期工作:
// 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循环会在您每次插入时都知道正确的地址头。
也许如果你返回头指针并正确地更新它,它应该可以解决你的问题。
+0
非常感谢,您的解决方案解决了我的问题。 – taoufeqreda
这是因为您只修改了'head'指针的副本。 – ilotXXI