C ++在链接列表中设置下一个节点指针

时间:2014-02-20 02:50:36

标签: c++ pointers

所以我在C ++中重新创建LinkedList,我正在尝试将指针更改为列表中的最后一个Node。这是我的重载+=运算符,其中发生了所有的魔法和错误。我有两种不同的方法来改变指针,但都抛出Unhandled exception at 0x00ee42f3 in Lab3.exe: 0xC0000005: Access violation writing location 0xccccccec.。发生了什么,我该如何解决?

void MyLinkedList::operator+=(const std::string& s)
{
    allocator<Node> a;
    Node* n = a.allocate(1);
    a.construct(n, s);


    if (first == NULL)
        first = n;
    else
    {
        (*last).next = n;    // crashes here
        (*last).SetNext(n);  //also will crash here, if the previous statement is removed
        last = n;
    }
}

为了进一步说明,它将通过并设置第一个Node,退出方法,下次调用它时将运行并输入else语句。此时有第二个Node,它在内存中分配并实例化。我要做的是将第一个Node* next中的Node指针设置为此新Node,但它会抛出异常。抱歉最初非常模糊。

2 个答案:

答案 0 :(得分:2)

我们不知道allocateSetNext具体实现。

如果没问题,请看这里:

if (first == NULL) 
{
    first = n;
    last = first; // You should assign last with the head node pointer.
}
...

也许有帮助。

答案 1 :(得分:1)

你的运营商+ =有很多问题。

1)运算符+ =应该返回对 this 的引用,而不是void。否则,+ = b是没有意义的。

MyLinkedList& MyLinkedList::operator+=(const std::string& s) 
{
    //...
    return *this;
}

2)其次,如果列表为空,则可能尚未初始化最后一个指针。

3)样式问题 - 你为什么要这样做:

(*last).next = n;  

当你应该这样做时:

last->next = n;  

相关问题