栈模板

 

#include <iostream>
#include <string.h>
using namespace std;

template<class T>
class STACK{
private:
 struct Node{
  T val;
  struct Node *next;
 };
 Node *top;
 int empty;
 public:
  STACK();
  void push(T x);
  void pop();
  T gettop();
  void print();
  int is_empty();
};

template<class T>
STACK<T>::STACK()
{
 top==NULL;
 empty=0;
}

template<class T>
void STACK<T>::push(T x)
{
 Node *p;
 p=new Node;
 if(p==NULL){
  cout<<"内存不足!"<<endl;
  exit(1);
 }
 p->val=x;
 p->next=top;
 top=p;
 
}

template<class T>
void STACK<T>::pop()
{
 Node *p;
 if(top==NULL)
 {
  cout<<"栈为空!"<<endl;
  exit(1);
  
 }
 p=top;
 top=top->next;
 delete p;
}

template<class T>
T STACK<T>::gettop()
{
 T x;
 if(top==NULL)
 {
  cout<<"栈为空!"<<endl;
  exit(1);
  
 }
 x=top->val;
 return x;
}

template<class T>
void STACK<T>::print()
{
 Node *p;
 p=top;
 if(p==NULL)
 {
  cout<<"栈为空!"<<endl;
  exit(1);
 }
 cout<<"栈中元素为:";
 while(p!=NULL)
 {
  cout<<p->val<<" ";
  p=p->next;
 }
 cout<<endl;
}

template<class T>
int STACK<T>::is_empty()
{
 return (top==NULL)?0:1;
}

int main()
{
 STACK<int>int_stack;
 int i;
 for(i=1;i<=10;i++)
  int_stack.push(i);
 // int_stack.print();
 
 int_stack.pop();
 cout<<"栈顶元素为:"<<int_stack.gettop()<<endl;
 
 
 STACK<char *>str_stack;
 str_stack.push("aajhjaas");
 str_stack.push("csaaa");
 // str_stack.print();
 cout<<"栈顶元素为:"<<str_stack.gettop()<<endl;
 str_stack.pop();
 cout<<"栈顶元素为:"<<str_stack.gettop()<<endl;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值