Linkedlist - 模板 - 指针

时间:2013-05-09 23:36:45

标签: c++ templates pointers linked-list

这段代码有什么问题?调试后我在runner = runner->next;收到错误,但我没看到它有什么问题。

void Linkedlist<T>::add(T item)
{
    if (root == 0)
    {
        root = new Node<T>(item);
        cout << "Add, Root is empty \n";
    }
    else
    {
        cout << "Add, Root  is not empty \n";
        Node<T> * runner = root;
        while (runner != 0)
        {
            runner = runner->next;
        }
        runner = new Node<T>(item);
    }
}

1 个答案:

答案 0 :(得分:2)

应该是这样的:

Node<T> * runner = root;
while (runner->next != NULL)
{
    runner = runner->next;
}
runner->next = new Node<T>(item);

您的代码只更改局部变量,而不是实际节点。 (请注意,runner->next是实际列表中的对象,而runner只是一个局部变量。)