(C++)堆栈的类模板

来源:互联网 发布:淘宝图书讲谈社 编辑:程序博客网 时间:2024/05/08 16:11
#include <iostream>#include <string>#define maxsize 100//默认堆栈的最大长度为100using namespace std;template<class T>class Stack{private:    T arr[maxsize];    int currentSize;//保存栈顶的位置public:    Stack():currentSize(0) {}//初始化栈顶为0    void push(T temp)//新元素入栈,该元素为栈顶元素(压栈)    {        arr[currentSize++]=temp;    }    T pop()//栈顶元素出栈    {        T temp=arr[currentSize-1];        arr[currentSize-1]=NULL;        currentSize--;        return temp;    }    bool empty()//判断该堆栈是否为空    {        return (currentSize==0)?true:false;    }    bool full()//判断该堆栈是否为满    {        return (currentSize==100)?true:false;    }    int size()//获得该堆栈的当前长度    {        return currentSize;    }    int top()//获得该堆栈当前的栈顶元素    {        return currentSize;    }};int main(){    //在主函数中分别测试int、char和double型数据    string type="";    int length,tempInt,n;    double tempDouble;    char tempChar;    while(cin>>type&&type!="STOP")    {        cin>>length;        if(type=="Int")        {            Stack<int> Int;            for(int i=0; i<length; i++)            {                cin>>tempInt;                if(Int.full()) cout<<"full!! ";                else Int.push(tempInt);            }            cin>>n;            for(int i=0; i<n; i++)            {                if(!Int.empty())cout<<Int.pop();                else cout<<"empty!!";                cout<<((i!=n-1)?" ":"\n");            }        }        else if(type=="Double")        {            Stack<double> Double;            for(int i=0; i<length; i++)            {                cin>>tempDouble;                if(Double.full()) cout<<"full!! ";                Double.push(tempDouble);            }            cin>>n;            for(int i=0; i<n; i++)            {                if(!Double.empty())cout<<Double.pop();                else cout<<"empty!!";                cout<<((i!=n-1)?" ":"\n");            }        }        else if(type=="Char")        {            Stack<char> Char;            for(int i=0; i<length; i++)            {                cin>>tempChar;                if(Char.full()) cout<<"full!! ";                Char.push(tempChar);            }            cin>>n;            for(int i=0; i<n; i++)            {                if(!Char.empty())cout<<Char.pop();                else cout<<"empty!!";                cout<<((i!=n-1)?" ":"\n");            }        }    }    return 0;}

Sample input

Int10 1 2 3 4 5 6 7 8 9 105Double5 0.8 4.5 6.2 5.4 12.97Char8 g h s a f o i p6STOP

Sample output

10 9 8 7 612.9 5.4 6.2 4.5 0.8 empty!! empty!!p i o f a s
原创粉丝点击