链式栈的实现
#include<iostream>
using namespace std;
template<class T>
struct Node
{
T data;
Node<T> *next;
};
template<class T>
class LinkStack
{
private:
Node<T>* top;
public:
LinkStack(){top=NULL;}
~LinkStack();
void Push(T x);//元素X入栈
T Pop();//栈顶元素出栈
T GetTop();//取栈顶元素
int StackEmpty();//测栈空
void ClearStack();//清除栈
void StackTranverse();//输出栈中元素
};
template<class T>
LinkStack<T>::~LinkStack()
{
Node<T>* q;
while(top)
{
q=top;
top=top->next;
delete q;
}
}
template<class T>
void LinkStack<T>::Push(T x)
{
Node<T> *s=new Node<T>;
s->data=x;
s->next=top;
top=s;
}
template<class T>
T LinkStack<T>::Pop()
{
T x;
Node<T>* p;
if(top==NULL)throw"下溢";
x=top->data;
p=top;
top=top->next;
delete p;
return x;
}
template<class T>
T LinkStack<T>::GetTop()
{
if(top==NULL)throw"栈中没有元素";
return top->data;
}
template<class T>
int LinkStack<T>::StackEmpty()
{
if(top==NULL)
return 1;
else
return 0;
}
template<class T>
void LinkStack<T>::ClearStack()
{
if(top==NULL)throw"没有内容";
else
{
top=NULL;
}
}
template<class T>
void LinkStack<T>::StackTranverse()
{
if(top==NULL)
cout<<"链表中为空!"<<endl;
Node<T> *p=top;
while(p)
{
cout<<"链式栈中的元素! "<<p->data<<endl;
p=p->next;
}
}
void main()
{
LinkStack<int> Link;
Link.Push(5);
Link.Push(6);
Link.StackTranverse();
Link.GetTop();
Link.StackTranverse();
cout<<"取出的栈顶元素"<<Link.Pop()<<endl;
Link.StackTranverse();
Link.ClearStack();
Link.StackTranverse();
}