栈的类模板实现

来源:互联网 发布:卖家淘宝店 编辑:程序博客网 时间:2024/05/16 04:13

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

0 0
原创粉丝点击