0
我使用了一个函数来将新节点插入到我的单链表中,但是当我插入后打印出节点内的所有值时,我只能得到第一节点: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
为什么?
这是因为您只修改了'head'指针的副本。 – ilotXXI