这段代码有什么问题?调试后我在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);
}
}
答案 0 :(得分:2)
应该是这样的:
Node<T> * runner = root;
while (runner->next != NULL)
{
runner = runner->next;
}
runner->next = new Node<T>(item);
您的代码只更改局部变量,而不是实际节点。 (请注意,runner->next
是实际列表中的对象,而runner
只是一个局部变量。)