#include <iostream>
#include <stdexcept>
#include <malloc.h>
using namespace std;
namespace my_space
{
template<class ElemType>
class stack
{
public:
stack(); //栈的初始化
~stack(); //栈的销毁
void clear(); //清空栈
bool empty() const;//判断栈是否为空
int length() const;//返回栈的长度
ElemType gettop() throw(out_of_range);//返回栈顶元素
void push(ElemType e); //插入e为新的栈顶元素
ElemType pop() throw(out_of_range); //删除栈顶元素
private:
class st
{
public:
ElemType *base;
ElemType *top;
int stacksize;
int length;
};
st sqstack;
static const int stack_init_size = 100; //存储空间初始化分配量
static const int stackincrement = 10; //存储空间分配增量
};
template<class ElemType>
stack<ElemType>::stack()
{
sqstack.base = new ElemType[stack::stack_init_size];
sqstack.top = sqstack.base;
sqstack.stacksize = stack::stack_init_size;
sqstack.length = 0;
}
template<class ElemType>
stack<ElemType>::~stack()
{
delete [] sqstack.base;
sqstack.length = 0;
sqstack.stacksize = 0;
}
template<class ElemType>
void stack<ElemType>::clear()
{
sqstack.top = sqstack.base;
sqstack.length = 0;
}
template<class ElemType>
bool stack<ElemType>::empty() const
{
return sqstack.length == 0;
}
template<class ElemType>
int stack<ElemType>::length() const
{
return sqstack.length;
}
template<class ElemType>
ElemType stack<ElemType>::gettop() throw(out_of_range)
{
if(sqstack.top == sqstack.base)
throw("stack is empty!");
return *(sqstack.top - 1);
}
template<class ElemType>
void stack<ElemType>::push(ElemType e)
{
if(sqstack.top - sqstack.base >= sqstack.stacksize)
{
sqstack.base = (ElemType*)realloc(sqstack.base, (sqstack.stacksize + stack::stackincrement)*sizeof(ElemType));
sqstack.top = sqstack.base + sqstack.stacksize;
sqstack.stacksize += stack::stackincrement;
}
*sqstack.top++ = e;
++sqstack.length;
}
template<class ElemType>
ElemType stack<ElemType>::pop() throw(out_of_range)
{
if(sqstack.base == sqstack.top)
throw("stack is empty");
--sqstack.length;
return *--sqstack.top;
}
}
int main()
{
return 0;
}
转载于:https://my.oschina.net/u/196018/blog/383785