为什么解引用节点会破坏我的链表

Why does dereferencing nodes break my linked-list?

本文关键字:我的 链表 引用 节点 为什么      更新时间:2023-10-16

所以我试图实现一个运行的工厂链表在c++

template<class T>
class Node
{
private:
    Node *next;
    T item;
public:
    Node(T item)
        : item(item)
    {
        this->next = NULL;
    }
    Node<T> add(T item) {
         this->next = new Node(item);
         return *this->next;
    }
    bool hasNext()
    {
        return this->next == NULL;
    }
    Node<T> getNext()
    {
        return *this->next;
    }
    T value()
    {
        return this->item;
    }
};
void main()
{
    Node<int> node(3);
    node.add(3).add(4);
    cout << node.value();
    cout << node.getNext().value();
    cout << node.getNext().getNext().value();
    cin.get();
}

但是我不能让它工作。特别是这一节:

    node.add(3).add(4);
    cout << node.value();
    cout << node.getNext().value();
    cout << node.getNext().getNext().value();

如果我改变我的addgetNext函数返回Node<T>*而不是Node<T>,它工作得很好。但是为什么解引用会导致代码中断呢?我认为.符号比->更有意义,但我不能让它工作。我做错了什么?

现在您正在复制您添加的节点,而不是返回您创建的实际节点。括号只是为稍后必须查看您的代码的其他人增加了一点清晰度。add函数需要这样修改:

Node<T>& add(T item) {
     this->next = new Node(item);
     return *(this->next);
}

或者您可以返回一个指向新创建节点的指针,但是这会破坏在main中使用.而不是->

同样需要对next()

进行类似的更改