我对这个非常简单的代码块有疑问。请给我你的建议。 (我的这个问题解决了,在解决这个问题时,id stakx 的人真的帮了我,唯一的问题是我在使用堆栈<treeNode>,当我仔细看到堆栈的推送方法时,有一个复制过程当我写 head->object=number 时,所以最后我做了一个指针堆栈,就像这个堆栈<treeNode*>,它确实解决了问题,我现在没有问题,我非常非常感谢 stakx 人。)
在代码之前,您需要提供以下树
替代文本 http://img44.imageshack.us/img44/7016/avlimage06.jpg
,如图所示,根为 8,堆栈有两个节点,即 6 和 4。我将此堆栈和根节点传递给以下代码
void Avltree::attachwithtree(treeNode* tree, Stack<treeNode>&s)
{
if(!s.isempty())
{
treeNode *stacknode;
stacknode=s.pop();
cout<<"\ninside the attachwithtree function, stack node is "<<stacknode->data;
stacknode->right=tree;//attaching the passed node to the right of popped node
root=stacknode;//setting the root to stack node which is the private data member of class
updatebalance(root);//this function is ok, it does not create problem
while(!s.isempty())
{
cout<<"\nstack is still not empty";
stacknode=s.pop();
cout<<"\nright side of "<<root->data<<" is "<<(root->right)->data;
//the below three lines causing the problem i don't know why,
root=stacknode;
treeNode* temp;
temp=root->right;
cout<<"\n\n\nthe right side of "<<temp->data<<" is now "<<(temp->right)->data;
updatebalance(root);
}
这是我正在使用的堆栈的 pop 方法的代码
template <class t>
t * Stack<t>::pop()
{
if(topelement!=NULL)
{
t* num;
current=topelement;
num=&(current->object);
topelement=topelement->preptr;
current=topelement;
return(num);
}
else
{
head=NULL;
}
}
这是堆栈的push方法的代码
template <class t>
void Stack<t>::push(t &number)
{
Node<t>* newNode=new Node<t>;
if(head==NULL)
{
head=newNode;
topelement=newNode;
current=newNode;
head->object=number;
head->preptr=NULL;
}
else
{
topelement=newNode;
newNode->preptr=current;
current=topelement;
newNode->object=number;
}
}