将链头作为栈顶,链栈不需要附设头结点。
链栈的声明
template <class T>
class LinkStack
{
public:
LinkStack( ) {top=NULL;};
~LinkStack( );
void Push(T x);
T Pop( );
T GetTop( );
bool Empty( );
private:
Node<T> *top;
}
入栈
template <class T>
void LinkStack<T>::Push(T x)
{
s=new Node<T>;
s->data=x;
s->next=top;
top=s;
}
出栈
template <class T>
T LinkStack<T>::Pop( )
{
if (top==NULL)
throw "下溢";
x=top->data;
p=top;
top=top->next;
delete p;
return x;
}
链栈的析构
template <class T>
LinkStack<T>::~LinkStack( )
{
while (top)
{
Node<T> *p;
p=top->next;
delete top;
top=p;
}
}