结点代码:
template<class ElemType>
struct Node {
ElemType data;
Node<ElemType>* next;
Node();
Node(const ElemType& e, Node<ElemType>* Link = NULL);
};
template<class ElemType>
Node<ElemType>::Node() {
next = NULL;
}
template<class ElemType>
Node<ElemType>::Node(const ElemType& e, Node<ElemType>* link) {
data = e;
next = link;
}
链栈功能实现:
#include"node.h"
template<class ElemType>
class LinkStack //链栈
{
protected:
//数据成员
Node<ElemType>* top;
int count;
public:
LinkStack();
virtual ~LinkStack();
int Length()const;
bool Push(const ElemType& e);
bool Pop(ElemType& e);
bool Pop();
void Clear();
bool Empty()const;
};
template<class ElemType>
LinkStack<ElemType>::LinkStack()
{
top = NULL;
count = 0;
}
template<class ElemType>
void LinkStack<ElemType>::Clear()
{
while (!Empty())
{
Pop();
}
}
template<class ElemType>
LinkStack<ElemType>::~LinkStack()
{
Clear();
}
template<class ElemType>
int LinkStack<ElemType>::Length()const
{
return count;
}
template<class 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<class ElemType>
bool LinkStack<ElemType>::Pop(ElemType& e)
{
if (Empty())
{
return false;
}
else
{
Node<ElemType>* oldTop = top;
e = oldTop->data;
top = oldTop->next;
delete oldTop;
count--;
return true;
}
}
template<class ElemType>
bool LinkStack<ElemType>::Pop()
{
if (Empty())
{
return false;
}
else
{
Node<ElemType>* oldTop = top;
top = oldTop->next;
delete oldTop;
count--;
return true;
}
}
template<class ElemType>
bool LinkStack<ElemType>::Empty()const
{
return count == 0;
}