#include <iostream>
#include <cstdlib>
using namespace std;
const int Size=5;
const int Increment=10;
//模板类
template<class T>
class Stack
{
public:
Stack(); //构造函数
T Pop(); //出栈
T GetTop(); //获得栈顶的元数
bool Visit(); //遍历打印栈内元数
bool IsFull(); //栈是否满
bool Push(T e); //入栈
bool IsEmpty(); //是否为空
~Stack(); //析构函数
private:
int size;
T* top;
T* base;
};
template<class T>
Stack<T>::Stack()
{
base=(T*)malloc(sizeof(T)*Size);
if(!base)
{
cout << "内存分配失败" << endl;
exit(OVERFLOW);
}
top=base;
size=Size;
}
template<class T>
T Stack<T>:: Pop()
{
if(top-base<=0)
{
cout << "栈内已经没有数据!" <<endl;
exit(1);
}
return *(--top);
}
template<class T>
T Stack<T>:: GetTop()
{
if(IsEmpty())
{
cout << "栈内已经没有数据!" <<endl;
exit(1);
}
return *(top-1);
}
template<class T>
bool Stack<T>:: Visit()
{
if(IsEmpty())
{
cout << "栈内已经没有数据!" <<endl;
exit(1);
}
T* p=--top;
cout << "元数出栈依次为:" <<endl;
for(p;p>=base;p--)
{
cout << " " << *(p);
}
cout << endl;
return true;
}
template<class T>
bool Stack<T>:: IsFull()
{
if(top-base==size)
return true;
else
return false;
}
template<class T>
bool Stack<T>:: Push(T e)
{
if(IsFull())
{
T* p=(T*)realloc(base,(size+Increment)*sizeof(T));
if(!p)
{
cout << "内存分配失败" << endl;
exit(OVERFLOW);
}
base=p;
top=base+size;
size+=Increment;
}
*(top++)=e;
return true;
}
template<class T>
bool Stack<T>:: IsEmpty()
{
if(top==base)
return true;
else
return false;
}
template<class T>
Stack<T>:: ~Stack()
{
delete [] base;
}
//测试代码
int main()
{
int e=0;
Stack<int> s;
for(int i=1;i<50;i++)
s.Push(i);
e=s.Pop();
cout<< e << " " <<s.GetTop() <<endl;
cout<< s.IsFull() << " " <<s.IsEmpty() <<endl;
s.Visit();
return 0;
}
栈的类模板实现
最新推荐文章于 2022-10-07 12:54:30 发布