两个栈来实现一个队列的C++代码
2015-08-30 10:27
806 查看
#include <iostream> #include <stack> using namespace std; // 用两个stack实现一个queue, 以int类型为例吧 class MyQueque { private: stack<int> s1; // s1负责入队 stack<int> s2; // s2负责出队 public: // 入队 void push(int x) { s1.push(x); } // 出队 void pop() { if(!s2.empty()) { s2.pop(); } else { while(!s1.empty()) { int tmp = s1.top(); s1.pop(); s2.push(tmp); } s2.pop(); } } // 取头 int front() { if(!s2.empty()) { return s2.top(); } while(!s1.empty()) { int tmp = s1.top(); s1.pop(); s2.push(tmp); } return s2.top(); } // 取尾 int back() { if(!s1.empty()) { return s1.top(); } while(!s2.empty()) { int tmp = s2.top(); s2.pop(); s1.push(tmp); } return s1.top(); } // 求大小 int size() { return s1.size() + s2.size(); } // 判断是否为空 bool empty() { if(s1.empty() && s2.empty()) { return true; } return false; } }; int main() { { MyQueque que; que.push(1); que.push(2); que.push(3); que.push(4); que.push(5); while(!que.empty()) { cout << que.front() << endl; que.pop(); } cout << "-------------------" << endl; } { MyQueque que; que.push(1); que.push(2); que.push(3); que.push(4); que.push(5); while(!que.empty()) { cout << que.size() << endl; que.pop(); } cout << "-------------------" << endl; } { MyQueque que; que.push(1); que.push(2); que.push(3); que.pop(); que.pop(); que.push(4); que.push(5); while(!que.empty()) { cout << que.front() << endl; que.pop(); } cout << "-------------------" << endl; } return 0; }
相关文章推荐
- C语言下的清屏函数
- C语言:链表
- C、C++语言容易出错的几个地方
- C++ 11 auto类型,不会自带引用
- C语言的指针*和引用&
- C++中vector使用
- C语言深入
- c++ 构造函数
- C语言新建临时文件和临时文件名的方法
- c语言指针初级
- Immediate Decodability(C++ Stl -----substr判断前缀)
- C语言字符串处理函数库
- Vc++ 控件用法总结之List Control
- C++ Primer : 第十二章 : 文本查询程序
- malloc、calloc、realloc的区别
- C++11 并发
- C语言中sizeof与strlen区别
- C++ string类
- 通过实例浅析Python对比C语言的编程思想差异
- LeetCode-Binary Tree Paths -解题报告