1

所以我追踪了这一点,评论部分给出了我的问题,我在链接列表的末尾,我想将 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;

}

4

1 回答 1

3

克里斯已经告诉你问题出在哪里。将指针指向 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)如果你变得相当聪明,它会更简单。例如,有一个Nodelike:

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;
}
于 2013-11-07T05:07:55.957 回答