【问题标题】:c: inserting new nodes to a singly linked list using a functionc:使用函数将新节点插入单链表
【发布时间】: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


【解决方案1】:

您在函数中传递指针,更新它而不返回它,在这种情况下,外部函数永远无法知道头部是否已更改。您还必须在 for 循环中适当地更新头部。

在你不使用函数的情况下,你的for循环每次插入时都知道正确的head地址。

如果您返回头指针并正确更新它,它应该可以解决您的问题。

【讨论】:

  • 非常感谢,您的解决方案解决了我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-20
  • 2019-04-26
  • 2013-02-06
  • 1970-01-01
  • 1970-01-01
  • 2020-05-11
  • 1970-01-01
相关资源
最近更新 更多