【发布时间】:2016-05-08 17:10:50
【问题描述】:
所以我确实已经设法解决了我的问题,但我无法理解到底是什么问题。我之前的代码是:
BinaryTree removePrivate(int x, BinaryTree *node)
{
if ((*node).m_key < x)
*(*node).m_right = removePrivate(x, (*node).m_right);
else if ((*node).m_key > x)
*(*node).m_left = removePrivate(x, (*node).m_left);
else
node= NULL ;
return *node;
}
它编译得很好,但是当它被调用时,事情就变糟了。返回 *node 时访问冲突;
我已经改成:
[*]= * 已添加,[ ]= * 已删除
BinaryTree [*]removePrivate(int x, BinaryTree *node)
{
if ((*node).m_key < x)
[ ](*node).m_right = removePrivate(x, (*node).m_right);
else if ((*node).m_key > x)
[ ](*node).m_left = removePrivate(x, (*node).m_left);
else
node= NULL ;
return [ ]node;
}
现在一切正常,但我真的不能 100% 确定为什么会更好。
【问题讨论】:
-
作为对读者的一项服务,您可能想指出哪些行的不同之处。
-
在您的旧代码中,当您的
node为NULL时,取消引用空指针具有未定义的行为,因为您无法取消引用任何内容。 -
尽量使用
node->m_right而不是(*node).m_right,如果可能的话why?更易读。还请在这篇文章中更正您的拼写。