#include<iostream>
using namespace std;
template <class t>
struct Node
{
Node*next;
tdata;
};
template <class t>
class Linkstack
{ Node<t>*top;
public:
Linkstack()
{ top=new Node<t>;
top=NULL;
}
~Linkstack(){}
voidpush(t x);
tpop();
tgettop()
{
if(top!=NULL)
returntop->data;
else
return0;
}
intempty()
{
intt=(top==NULL?1:0);
if(t==0)
cout<<"这是一个空链栈"<<endl;
}
voidprint();
};
template <class t>
void Linkstack<t>::push(t x)
{
Node<t>*s;
s=newNode<t>;
s->data=x;
s->next=top;//新栈顶指向旧栈顶,链栈的next指针是指向前一个已经在栈中的元素的
top=s;
}//链栈的进栈分两步,第一步是处理新结点s的后继,这个后继就是原本的栈顶结点;第二,将栈顶的指针top重新指向新结点s
template <class t>
t Linkstack<t>::pop()
{ Node<t>*p;
if(top==NULL)throw"下溢";
tx=top->data;
p=top;
top=top->next;//将栈顶结点摘链
deletep;
returnx;
}
template <class t>
void Linkstack<t>::print()
{
Node<t>*p;
p=top;
cout<<"将所有元素从后往前输出是:";
while(p)
{
cout<<p->data<<"";
p=p->next;//改变栈顶
}
}
int main()
{
Linkstack<int>link;
link.empty();
link.push(1);
link.push(3);
link.push(5);
link.print();
cout<<endl<<"删除栈顶元素:"<<link.pop()<<endl;
cout<<"栈顶元素是:"<<link.gettop()<<endl;
link.print();
cout<<endl;
return0;
![](https://i-blog.csdnimg.cn/blog_migrate/04847422f3a98495b21e3c7b624d26f2.png)