(C++)堆栈的类模板

xiaoxiao2021-02-27  168

#include <iostream> #include <string> #define maxsize 100//默认堆栈的最大长度为100 using 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

Int 10 1 2 3 4 5 6 7 8 9 10 5 Double 5 0.8 4.5 6.2 5.4 12.9 7 Char 8 g h s a f o i p 6 STOP

Sample output

10 9 8 7 6 12.9 5.4 6.2 4.5 0.8 empty!! empty!! p i o f a s
转载请注明原文地址: https://www.6miu.com/read-11392.html

最新回复(0)