[英]Destructor for Binary Search Tree
I am making a destructor for a binary search tree. 我正在为二进制搜索树创建析构函数。 I hit an infinite loop with the first while-loop because head's left pointer never gets set to NULL when kill is set to NULL.
我在第一个while循环中遇到了一个无限循环,因为在kill设置为NULL时,头部的左指针永远不会设置为NULL。 Why is this and how can I fix it?
为什么会这样,我该如何解决?
Thanks in advance! 提前致谢!
BST::~BST()
{
Node* kill = head;
/*
While-loop runs until all of head's left branch has been deleted
*/
while(head->get_left() != NULL)
{
kill = head->get_left();//Set the pointer variable kill to heads left node.
/*
While-loop moves the kill pointer to a bottom node with that has no children
*/
while(kill->get_left() != NULL && kill->get_right() != NULL)
{
if(kill->get_left() != NULL)
{
kill = kill->get_left();
}
if(kill->get_right() != NULL)
{
kill = kill->get_right();
}
}
delete kill;//deletes the bottom node with no children
kill = NULL;
}
kill = head;
/*
While-loop runs until all of head's right branch has been deleted
*/
while(head->get_right() != NULL)
{
kill = head->get_right();//Sets the kill pointer to head's right node
/*
While-loop moves the kill pointer to a bottom node with no children
*/
while(kill->get_left() != NULL && kill->get_right() != NULL)
{
if(kill->get_left() != NULL)
{
kill = kill->get_left();
}
if(kill->get_right() != NULL)
{
kill = kill->get_right();
}
}
delete kill;//deletes the bottom node with no children
kill = NULL;
}
delete kill;//deletes the head node
}
Looks like you can simplify your destructor. 看起来您可以简化析构函数。 Implement destructor for
Node
. 为
Node
实现析构函数。 Something like this: 像这样:
Node::~Node()
{
delete left;
left = NULL;
delete right;
right = NULL;
}
In this case your BST::~BST()
will be: 在这种情况下,您的
BST::~BST()
将为:
BST::~BST()
{
delete head;
head = NULL;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.