#include <iostream>
using namespace std;
const int INITSIZE=10;
const int INCREASESIZE=10;
template<class ElemType>class MyStack
{
public:
~MyStack();
void init();
void destroy();
bool isEmpty();
void push(ElemType );
void pop(ElemType &);
void getTop(ElemType &);
void print();
void clear();
private:
int top,capacity;
ElemType *base;
};
template<class ElemType>
MyStack<ElemType>::~MyStack()
{
if(base)delete []base;
}
template<class ElemType>
void MyStack<ElemType>::init()
{
base = new ElemType[INITSIZE];
top = -1;
capacity = INITSIZE;
}
template<class ElemType>
void MyStack<ElemType>::destroy()
{
delete []base;
base = 0;
}
template<class ElemType>
void MyStack<ElemType>::push(ElemType e)
{
if(top+1 == capacity)
{
ElemType *tmp = new ElemType[capacity+INCREASESIZE];
for(int i=0;i<capacity;i++)
*(tmp+i)=*(base+i);
delete []base;
base = tmp;
}
base[++top]=e;
}
template<class ElemType>
void MyStack<ElemType>::pop(ElemType &e)
{
if(!isEmpty())
{*e=base[top--];}
else cout<<"empty"<<endl;
}
template<class ElemType>
bool MyStack<ElemType>::isEmpty()
{
return top==-1;
}
template<class ElemType>
void MyStack<ElemType>::getTop(ElemType &e)
{
if(!isEmpty()){*e=base[top];}
else{cout<<"GetTop error"<<endl;}
}
template<class ElemType>
void MyStack<ElemType>::print()
{
for(int i=top;i>=0;i--)
cout<<base[i]<<' ';
cout<<endl;
}
template<class ElemType>
void MyStack<ElemType>::clear()
{
top = -1;
}
使用C++模板类实现栈数据结构
最新推荐文章于 2022-10-07 12:54:30 发布
本文展示了如何使用C++模板类来实现栈数据结构。通过定义一个名为MyStack的模板类,包含了初始化、销毁、判断栈空、压栈、弹栈、获取栈顶元素、打印栈和清空栈等基本操作。代码中还包括了动态扩容的实现。
摘要由CSDN通过智能技术生成