所以我查到了这个,评论部分给出了我的问题,我在链接列表的末尾,我想将 nullptr 更改为新节点 *q 但我一直返回原始链接列表没有新添加的节点。
Node* append( int x, Node* p ) {
Node *q=new Node;
Node *head=p;
if(p==nullptr) {
p=q;
q->value=x;
}
while (p!=nullptr) {
p=p->next;
}
//arrived at NULL ptr
q=p->next; //<---this is causing my program to crash.
q->value=x;
q->next=nullptr;
return head;
最佳答案
Chris 已经告诉您问题所在。将指针指向 null,然后取消引用它,您将得到您所要求的:未定义的行为
这会做你想做的事,代码要少得多。
Node* append( int x, Node* p )
{
Node **pp = &p;
while (*pp)
pp = &(*pp)->next;
*pp = new Node;
(*pp)->value = x; // this really should be a Node::Node() parameter
(*pp)->next = nullptr; // ... and this should be set in Node::Node as well
return p;
}
如果你让 Node::Node(int x)
变得相当智能,它会更简单。例如,对于 Node
如下:
struct Node
{
int val;
Node *next;
Node(int val) : val(val), next() {}
};
然后您可以简单地执行此操作:
Node* append( int x, Node* p )
{
Node **pp = &p;
while (*pp)
pp = &(*pp)->next;
*pp = new Node(x);
return p;
}
关于c++ - 追加函数和 nullptr 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19828262/