/*-------- 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;
}