//Node.h
template<typename ElemType>
struct Node
{
ElemType data;
Node<ElemType> *next;
Node();
Node(ElemType item,Node<ElemType> * link=NULL);
};
template<typename ElemType>
Node<ElemType>::Node()
{
next=NULL;
}
template<typename ElemType>
Node<ElemType>::Node(ElemType item,Node<ElemType> *link)
{
data=item;
next=link;
}
//LinkStack.h
template<typename ElemType>
class LinkStack
{
protected:
Node<ElemType> *top;
int count;
public:
LinkStack();
virtual ~LinkStack();
int Length() const;
bool Empty() const;
void Clear();
void Traverse(void (*visit)(const ElemType &)) const;
bool Push(const ElemType &e);
bool Top(ElemType &e) const;
bool Pop(ElemType &e);
LinkStack(const LinkStack<ElemType> ©);
LinkStack<ElemType> &operator=(const LinkStack<ElemType> ©);
};
template<typename ElemType>
LinkStack<ElemType>::LinkStack()
{
top=NULL;
count=;
}
template<typename ElemType>
LinkStack<ElemType>::~LinkStack()
{
Clear();
}
template<typename ElemType>
int LinkStack<ElemType>::Length() const
{
return count;
}
template<typename ElemType>
bool LinkStack<ElemType>::Empty() const
{
return top==NULL;
}
template<typename ElemType>
void LinkStack<ElemType>::Clear()
{
ElemType tmpElem;
while(!Empty())
Pop(tmpElem);
}
template<typename ElemType>
void LinkStack<ElemType>::Traverse(void (*visit)(const ElemType &))const
{
Node<ElemType> *tmpPtr;
LinkStack<ElemType> tmpS;
for(tmpPtr=top;tmpPtr!=NULL;tmpPtr=tmpPtr->next)
tmpS.Push(tmpPtr->data);
for(tmpPtr=tmpS.top;tmpPtr!=NULL;tmpPtr=tmpPtr->next)
(*visit)(tmpPtr->data);
}
template<typename ElemType>
bool LinkStack<ElemType>::Push(const ElemType &e)
{
Node<ElemType> *newTop=new Node<ElemType>(e,top);
if(newTop==NULL)//内存耗尽
return false;
else
{
top=newTop;
count++;
return true;
} }
template<typename ElemType>
bool LinkStack<ElemType>::Top(ElemType &e)const
{
if(Empty())
return false;
else
{
e=top->data;
return true;
} }
template<typename ElemType>
bool LinkStack<ElemType>::Pop(ElemType &e)
{
if(Empty())
return false;
else
{
Node<ElemType> *old_top=top;
top=old_top->next;
e=old_top->data;
count--;
delete old_top;
return true;
} }
template<typename ElemType>
LinkStack<ElemType>::LinkStack(const LinkStack<ElemType> ©)
{
if(Empty())
{
top=NULL;
count=;
}
else
{
top=new Node<ElemType>(copy.top->data);
count=copy.count;
node<ElemType> *buttomPtr=top;
for(Node<ElemType> *tmpPtr=copy.top->next;tmPtr!=NULL;tmpPtr=tmpPtr->next)
{
buttomPtr->next=new Node<ElemType> (tmpPtr->data);
buttomPtr=buttomPtr->next;
} }
}
template<typename ElemType>
LinkStack<ElemType> &LinkStack<ElemType>::operator=(const LinkStack<ElemType> ©)
{
if(©!=this)
{
if(copy.Empty())
{
top=NULL;
count=;
}
else
{
Clear();
top=new Node<ElemType>(copy.top->data);
count=copy.count;
Node<ElemType> *buttomTop=top;
for(Node<ElemType> *tmpPtr=copy.top->next;tmpPtr!=NULL;tmpPtr=tmpPtr->next)
{
buttomTop->next=new node<ElemType>(tmpPtr->data);
buttomTop=buttomTop->next;
} }
} }