我一直在尝试一个函数,在该函数中,您将一个节点添加到链表的末尾,虽然看起来很成功,但它似乎只填充头值,而不继续链。这个函数会影响列表,返回到主函数,然后访问其他函数的同一个链表,但我只能访问链表的头。
关于为什么会发生这种情况,我已经看了很多过去的问题和例子,但没有一个和我有完全相同的问题和情况
这是在addNode函数中,节点为*&头作为主要功能的输入。为此,我已经用输入填充了A的值,这是正常的。
node *A = new node, *ptr = head;
A->costs1=costs;
A->next = nullptr;
ptr = head;
if (head == nullptr)
{
head = A;
}
else{
while (ptr->next!=nullptr){
ptr=ptr->next;
}
ptr = A;
}
这是结构,我减少了变量的数量,这样它就不会变得太复杂:
struct node
{
string costs1;
node *next;
};
我可以很好地访问head->costs1,这是正确的,但如果我尝试访问head->next->costs1.它最终一无所获。
您需要设置ptr->next = A
,而不是ptr = A
。您当前的代码并没有将A对象添加到列表中,它只是将ptr
指针设置为该对象,但没有使用该指针。
lxop的答案应该可以解决问题,但还有更好的选择。我试着在评论中解释,但评论很难解释任何复杂的事情。
所以我们开始了:
//set up the new node.
// Nothing new here.
node *A = new node;
A->costs1=costs;
A->next = nullptr;
// Find the null next pointer (the end of the list)
// head is a pointer to the next node, just like any other next pointer.
// this hides the difference between head and next so we can use the exact
// same code for both. This reduces the number of cases we need to handle.
// In addition by having a pointer to the next pointer, we are tracking
// node insertion points, not nodes. When you are tracking the nodes, you're
// forced to keep track of the current node and the previous node so you
// can get access to the previous node's next so you can link the new new
// node to it. With the pointer to pointer, you have a pointer to previous's
// next, you can assign right to it AND use it as the current node.
node **ptr = &head; // get pointer to pointer to next node, the first node
// in this case
while (*ptr != nullptr){ // test that there is a next node, if there isn't
// we've found the end.
ptr = &(*ptr)->next; // if there is, advance to point at it's next.
}
// link in the new node
// when there are no more nodes to be had, ptr points right at the next node
// we need to update
*ptr = A; // so we update it.
在这里,它再次没有所有的解释清楚:
//set up the new node
node *A = new node;
A->costs1=costs;
A->next = nullptr;
// Find the null next pointer (the end of the list)
node **ptr = &head;
while (*ptr != nullptr){
ptr = &(*ptr)->next;
}
// link in the new node
*ptr = A;