动态栈的实现(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; }
相关文章推荐
- C语言实现哈夫曼编码
- C++判断一个数是否为整数
- C++无序元素直接排序法
- C++代码重构——从C global到C++ template
- C++将二叉树转为双向链表及判断两个链表是否相交
- hdu1097
- C++实现查找二叉树中和为某一值的所有路径的示例
- C语言——希尔排序
- 约瑟夫环问题(结构体指针实现)
- hdu1005
- C++ previous declaration of...with 'C++' linkage
- C++使用STL:慎重选择删除元素的方法
- C++/MFC修行之路(3) MFC中各个类的互相访问/取指针
- C++扫雷
- POJ3461 字符串双HASH
- USACO 5.1.1 凸包参考程序
- C++/MFC修行之路(2) 自定义消息
- C/C++ extern关键字用法
- C语言中,一级指针,二级指针,数组,一位数组指针,二位数组指针浅谈
- ISBN编码