c++ - 链表,无法将节点链接到头部

标签 c++ linked-list

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

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;

关于c++ - 链表,无法将节点链接到头部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29873101/

相关文章:

c++ - boost::asio 是否进行过多的小堆分配或者我错了吗?

c++ - 对“WinMain@16”的 undefined reference 是什么

c++ - boolean 赋值运算符

c++ - 替换字符串中的空格 C++ boost 问题

c++ - 在关闭应用程序期间正确关闭可能运行很长时间的线程

c - 打印链表的不同函数

c - C 链表中的冒泡排序

java - 递归地将新节点添加到 LinkedList 的末尾?

c++ - 为什么通过错误分配指针来连接两个链表?

c++ - C++ 中的链接类?