栈(C++模板类实现)

 

/*--------   Stack.h   --------   */
#ifndef _STACK_H
#define _STACK_H
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
template <class DataType>
class Stack{
public:
 Stack();
 void Push(DataType e);     //插入为e的新栈顶元素
 int Pop(DataType &e);      //删除栈顶元素
 int GetTop(DataType &e);   //取出栈顶元素
 int StackEmpty();          //判断是否为空栈
 void DestroyStack();       //栈被销毁
private:
 DataType *base;
 DataType *top;
 int stacksize;
};

template <class DataType>
Stack<DataType>::Stack()
{
 if(!(base=(DataType*)malloc(sizeof(DataType)))) exit(1);
 top=base;
 stacksize=STACK_INIT_SIZE;
}
template <class DataType>
void Stack<DataType>::Push(DataType e)
{
 if(top-base>=stacksize){
  if(!(base=(DataType*)realloc(base,(stacksize+STACKINCREMENT)*sizeof(DataType)))) exit(1);
  top=base+stacksize;
  stacksize+=STACKINCREMENT;
 }
 *top++=e;
}
template <class DataType>
int Stack<DataType>::Pop(DataType &e)
{
 if(top==base) return 0;
 e=*--top;
 return 1;
}
template <class DataType>
int Stack<DataType>::GetTop(DataType &e)
{
 if(top==base) return 0;
 e=*(top-1);
 return 1;
}
template <class DataType>
int Stack<DataType>::StackEmpty()
{
 return top==base? 1:0;
}
template <class DataType>
void Stack<DataType>::DestroyStack()
{
 free(base);
}

#endif

/*----------------   http://ourys.com原创,做人要厚道,转帖请标明来处,作者Hector -------*/

/*---------------     基本测试文件    -----------------*/
#include <iostream>
using namespace std;
#include "Stack.h"
int main()
{
 Stack<int> my;
 int a[2];
 my.Push(5);
 my.Push(4);
 my.Pop(a[0]);
 my.GetTop(a[1]);
 cout<<a[0]<<a[1]<<endl;
 my.DestroyStack();
 return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值