您的位置:首页 > 编程语言 > C语言/C++

动态栈的实现(C++)

2016-02-04 18:32 681 查看
#include <iostream>
using namespace std;

const int STACKINCREMENT = 20;
const int STACK_INIT_SIZE = 10;

template <typename ElemType>
class MyOwnStack
{
public:
MyOwnStack();
virtual ~MyOwnStack();
int stackLen();
void emptyStack();
void realloc();
void Push(ElemType);
ElemType  Pop();
protected:
ElemType *base;
ElemType *top;
int stackSize;
};

template <typename ElemType>
MyOwnStack<ElemType>::MyOwnStack()
{
base = new ElemType[STACK_INIT_SIZE];
top = base;
stackSize = STACKINCREMENT;
}

template <typename ElemType>
MyOwnStack<ElemType>::~MyOwnStack()
{
delete[] base;
}

template <typename ElemType>
int MyOwnStack<ElemType>::stackLen()
{
return top-base;
}

template <typename ElemType>
void MyOwnStack<ElemType>::emptyStack()
{
top = base;
}

template <typename ElemType>
void MyOwnStack<ElemType>::realloc()
{
ElemType* p = new ElemType[stackSize+STACKINCREMENT];
ElemType* q = p;
while(base!=top){
*q = *base;
q++;
base++;
}
delete[] base;
top = q;
base = p;
stackSize+=STACKINCREMENT;
}

template <typename ElemType>
void MyOwnStack<ElemType>::Push(ElemType e)
{
if(top - base >= stackSize){
realloc();
}
(*top) = e;
top++;
}

template <typename ElemType>
ElemType MyOwnStack<ElemType>::Pop()
{
if(top == base){
cout<<"The Stack is empty.\n";
exit(1);
}
return *--top;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: