我有一个涉及AVL树和等级树的任务。 在这个特定的任务中,我们需要实现一个Rank AVL树,它保存节点中的另一个信息。
我有这个问题:
我做了一个AVL树和Rank树,我选择使用继承。
在Rank树的“Insert”函数中,我调用另一个名为“setAllHeights”的函数,它接收一个节点作为参数。
但是,当我看到参数的调试器中的值时,我看到函数接收到NULL指针。
我不明白为什么,因为在我进入“setAllHeights”函数之前,我检查了参数的值,它绝对不是NULL。
可能是什么问题,为什么会发生?
我将非常感谢您的帮助。函数调用后,C++指针在继承中丢失了值。
功能插入的代码:
template<class T, class Compare>
bool RAVL<T, Compare>::insert(const T& data) {
if (root == NULL) {
root = new (nothrow) RNode<T, Compare>(data, NULL);
if (!root)
throw AllocationError();
size++;
return true;
}
Compare cmp;
RNode<T, Compare> *v;
if (find(data, &v))
return false;
if (cmp(v->data, data)) {
v->right = new (nothrow) RNode<T, Compare>(data, v);
if (!v->right)
throw AllocationError();
} else {
v->left = new (nothrow) RNode<T, Compare>(data, v);
if (!v->left)
throw AllocationError();
}
Node<T,Compare> * n=v;
AVL<T,Compare>::setAllHeights(n);
rebalance(v);
size++;
return true;
}
的setAllHeights函数的代码:
template<class T, class Compare>
void AVL<T, Compare>::setAllHeights(Node<T, Compare> *n) {
if (n == NULL) {
return;
}
setHeight(n);
setAllHeights(n->parent);
}
解决此类问题的正确工具是您的调试器。在*堆栈溢出问题之前,您应该逐行执行您的代码。如需更多帮助,请阅读[如何调试小程序(由Eric Lippert撰写)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,您应该\编辑您的问题,以包含一个[最小,完整和可验证](http://stackoverflow.com/help/mcve)示例,该示例再现了您的问题,以及您在调试器。 –
这正是我所做的..我在调试器中看到该函数接收NULL指针..我只是不明白为什么它发生。 – kidneyThief
你在做一个调试版本吗?你可以在优化版本中看到有些奇怪的东西。 –