#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;
}
动态栈的实现(C++)
最新推荐文章于 2022-04-26 17:15:39 发布