链表,无法将节点链接到头

linkedlist, cannot link the node to head

本文关键字:链接 节点 链表      更新时间:2023-10-16

我只是在某个地方迷失了方向,我无法弄清楚我的代码出了什么问题。下面的函数是我将节点放入列表的附加函数。

void AppendNode(struct s_list *list, unsigned int data)
{
    if (list == nullptr)
        return;
    struct s_node *tempHead = list->head;
    struct s_node *newNode = new s_node;
    newNode->next = nullptr;
    while (tempHead != nullptr)
        tempHead = tempHead->next;
    tempHead = newNode;
}

我调用了这个函数 100 次,它根本不会将新节点与当前列表链接起来。找到问题应该不难,但我太糟糕了。给我一些建议。谢谢。

/

/*****

感谢您的所有回复,但我仍然有同样的问题。我已经为我的列表分配了头节点,然后将其传递给函数。现在,我更改为直接传递列表负责人,不再列表,但仍然有同样的问题......

void AppendNode(struct s_node *head, unsigned int data)
{
    if (head == nullptr)
        return;
    struct s_node *tempHead = head;
    struct s_node *newNode = new s_node;
    newNode->next = nullptr;
    while (tempHead != nullptr)
        tempHead = tempHead->next;
    tempHead = newNode;
}

您的tempHead在列表末尾运行;此函数中的任何内容都不会更改列表。

首先处理空列表的情况:

if(list->head == NULL)
{
  list->head = newNode;
  return;
}

然后谨慎前进:

while (tempHead->next != nullptr)
  tempHead = tempHead->next;
tempHead->next = newNode;
或者,

如果您尝试将节点附加到列表的末尾,只需执行以下操作:

while (tempHead->next != nullptr)
    tempHead = tempHead->next;
tempHead->next = newNode;