I am building a simple tree by pointer
this tree would only have one child and one sibling
if you call addChild more than once on the same node, it would add a sibling
if you call addchild more than two times(assume it is three times) on the same node
it would add a sibling on the "next" pointer which point to "0"(it would traverse the tree)

Below is my code

``````template<typename T>
class node
{
public:
explicit node(T value_);
~node();

private:
T value;
node<T>* prev;
node<T>* child;
node<T>* next;
};

template<typename T>
node<T>::node(T value_)
:value(value_),
prev(0),
child(0),
next(0)
{}

template<typename T>
node<T>::~node()
{
prev = 0;
if(child)
delete child;

if(next)
delete next;

child = 0;
next = 0;
}

int callTime = 0;
template<typename T>
{
++callTime;

cout<<"callTime = "<<callTime<<endl;
if(child)
cout<<"child->value = "<<child->value<<endl;
else
cout<<"child = 0"<<endl;

[b]//the puzzle of mine, next would always point to "0"[/b]
if(next)
cout<<"next->value = "<<next->value<<endl;
else

if(!child)
child = Node;
else
}

template<typename T>
{
[b]//the most mysterious way is, in this function body, next
//would not always be zero?[/b]
if(!next)
next = Node;

else
{
node<T>* ptr = next;
while(ptr->next)
ptr = ptr->next;

if(!ptr->next)
{
ptr->next = Node;
Node->prev = ptr;
}
}
}

void simpleTree()
{
node<int>* root = new node<int>(1);

delete root;
}``````

But if I alter the code a little bit
just ignore the function addSibling then the next would not point to 0 again

``````template<typename T>
class node
{
public:
explicit node(T value_);
~node();

private:
T value;
node<T>* prev;
node<T>* child;
node<T>* next;
};

template<typename T>
node<T>::node(T value_)
:value(value_),
prev(0),
child(0),
next(0)
{}

template<typename T>
node<T>::~node()
{
prev = 0;
if(child)
delete child;

if(next)
delete next;

child = 0;
next = 0;
}

int callTime = 0;
template<typename T>
{
++callTime;

cout<<"callTime = "<<callTime<<endl;
if(child)
cout<<"child->value = "<<child->value<<endl;
else
cout<<"child = 0"<<endl;

[b]//next would not point to "0" again, what is going on?[/b]
if(next)
cout<<"next->value = "<<next->value<<endl;
else

if(!child)
child = Node;
else
{
if(!next)
next = Node;

else
{
node<T>* ptr = next;
while(ptr->next)
ptr = ptr->next;

if(!ptr->next)
{
ptr->next = Node;
Node->prev = ptr;
}
}
}

void simpleTree()
{
node<int>* root = new node<int>(1);

delete root;
}``````

Although the result are fine, but I want to know why?
What is happening?Did I did any mistakes?
Thanks a lot

1
Contributor
1
2
Views
7 Years
Discussion Span
Last Post by stereomatching

I solved it

``child->addSibling(Node);``

sould be

``addSibling(Node);``