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