Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

pointer to a class

Status
Not open for further replies.

jimberger

Programmer
Jul 5, 2001
222
GB
Hello

i am trying to build a tree
I have a pointer to a class which represent nodes in the tree
the class' private data consists of a int value, a left pointer, a right pointer and a parent pointer. However when i assign the parent pointer to null like node->parent = NULL the node value itself gets assigned to NULL. so the left and right pointers are also null etc... is they any obvious reason why this should happen? i can post the code if needed...
thanks for your help
jim
 
Let's see the code Jim [santa2]
tellis.gif

[sup]programmer (prog'ram'er), n A hot-headed, anorak wearing, pimple-faced computer geek.[/sup]​
 
class Node
{
protected:
int value;
Node* leftChild;
Node* rightChild;
Node* parent;
public:
Node();
...
};

// constructor for the class

Node::Node()
{
value = 0;
leftChild = rightChild = parent = NULL;
}

===
That's the only place where you need to make the parent point to nothing. I guess your "node->parent = NULL" would mean that node is the current node and making its parent NULL would mean that you are going to lose both children still allocated in the memory with no possibility to be deleted, memory leaks will happen. Best Regards,

aphrodita@mail.krovatka.ru {uiuc rules}
 
Like aphrodita suggested, a tree is a linked data structure. I'll elaborate, and use a linked list for ease of typing, but here's what I suspect is happening.

The list (applicable to a tree in a similar way) looks like this:

NODE1 -> NODE2 -> NODE3 -> NODE4

If you assign NODE2 to NULL, then you have a structure like this:

NODE1 -> NULL

Since NULL points to nothing, you lose track of NODE3 and NODE4, which results in a memory link.

Deleting the parent node of a tree is difficult to handle, and a somewhat nasty algorithm would be required to reassign the pointers of the resulting mess (you'd need to reassign the pointer to the parent to one of the child nodes, shift both of the pointers of that node, then search the values beneath it for the proper place to assign a third misplaced pointer... ask if you want me to explain).

I can help you develop the logic if you need it (because it sounds fun).
 
If you want to delete one node with all his children and brothers - it is simple - destructors will make all necessary deletions recursively. Like BoulderBum said, it is difficult, when you want to keep children and brothers - you must decide, where to place them.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top