使用C++模板类实现栈数据结构

本文展示了如何使用C++模板类来实现栈数据结构。通过定义一个名为MyStack的模板类,包含了初始化、销毁、判断栈空、压栈、弹栈、获取栈顶元素、打印栈和清空栈等基本操作。代码中还包括了动态扩容的实现。
摘要由CSDN通过智能技术生成

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值