0

这段代码有什么问题?调试后出现错误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);
    }
}
4

1 回答 1

2

它应该是这样的:

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

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

于 2013-05-09T23:42:19.167 回答