StackNode.h
template<typename Type> class LinkStack;
template<typename Type> class StackNode
{
private:
Type data;
StackNode<Type> *pnext;
private:
friend class LinkStack<Type>;
StackNode() {};
StackNode(Type item, StackNode<Type> *next=NULL):data(item), pnext(next) {}
~StackNode()
{
cout<<"析构函数"<<endl;
pnext = NULL;
}
};
LinkNode.h
#include "StackNode.h"
template<typename Type> class LinkStack
{
public:
LinkStack():ptop(NULL) {}
~LinkStack()
{
cout<<"~LinkStack"<<endl;
MakeEmpty();
}
public:
void MakeEmpty();
void Push(const Type item);
Type Pop();
Type GetTop() const;
void Print();
bool IsEmpty() const
{
return ptop == NULL;
}
private:
StackNode<Type> *ptop;
};
template<typename Type>
void LinkStack<Type>::MakeEmpty()
{
if( IsEmpty() )
{
cout<<"the link stack has been empty"<<endl;
exit(1);
}
StackNode<Type> *pdel;
while(ptop != NULL)
{
pdel =ptop;
ptop = ptop->pnext;
delete pdel;
}
}
template<typename Type>
void LinkStack<Type>::Push(const Type item)
{
StackNode<Type> *ele = new StackNode<Type>;
ele->data = item;
ele->pnext= ptop;
ptop = ele;
//ptop = new StackNode<Type>(item, ptop);
}
template<typename Type>
Type LinkStack<Type>::Pop()
{
if( IsEmpty())
{
cout<<"cannot pop the stack node"<<endl;
exit(1);
}
StackNode<Type> *pdel =ptop;
ptop=ptop->pnext;
Type item = pdel->data;
delete pdel;
return item;
}
template<typename Type>
Type LinkStack<Type>::GetTop() const
{
if( IsEmpty() )
{
cout<<"the link stack is empty"<<endl;
exit(1);
}
return ptop->data;
}
template<typename Type>
void LinkStack<Type>::Print()
{
cout<<"top";
StackNode<Type> *pmov=ptop;
while(pmov != NULL)
{
cout<<"-->"<<pmov->data;
pmov = pmov->pnext;
}
cout<<"-->buttom"<<endl;
}
顺便测试了下析构函数,只有在对象释放时才会调用析构函数。