(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
阅读全文
0 0
- (C++)堆栈的类模板
- 用模板写的堆栈类
- 堆栈类模板的创建和使用
- 堆栈的基本功能模板
- 类模板实现堆栈
- C++模板堆栈类
- 堆栈类模板
- 模板类实现堆栈:
- C++_模板举例_使用模板实现集合类(堆栈)
- C++_模板举例_使用模板实现集合类(堆栈)
- c++堆栈类模板实现
- 堆栈和内存的关系(C++)
- 堆栈的实现(c语言)
- 堆栈的C实现
- C语言的堆栈
- c语言的堆栈
- c的堆栈-转载
- 模板堆栈
- 合并区间
- java基础知识点回顾笔记(日更)
- 对文件进行操作
- python新式类和经典类的区别?
- nodejs 连接 MySQL
- (C++)堆栈的类模板
- 留个纪念傻傻的博客
- 链表排序 1.0粗糙版
- LeetCode 75. Sort Colors
- php魔术函数__autoload
- STM32(1)
- 关于c++面向对象重债覆盖隐藏和虚函数表
- 读取CSV XLSX XLS文件
- java动态规划最小路径和