我只是在某个地方的中间迷失了方向,我无法弄清楚我的代码出了什么问题。下面的函数是我的append函数,用于将节点放入列表。
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/