链栈

#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;

}

      

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值