【发布时间】:2017-10-28 20:13:11
【问题描述】:
我使用函数将新节点插入到我的单链表中,但是当我在插入后打印出节点内的所有值时,我只得到第一个节点的值:
// 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
为什么?
【问题讨论】:
-
那是因为你只修改了
head指针的一个副本。
标签: c linked-list singly-linked-list