两个栈模拟一个队列和两个队列模拟一个栈(c++实现)
2017-05-25 00:04
507 查看
c++实现两个栈模拟队列和两个队列模拟一个栈(剑指offer第七题(P59-P62))
#include <iostream>#include <stack>#include <queue>#include <bits/stdc++.h>using namespace std;class Queue {public:void in(const int &k);int del();private:stack<int> sta1;stack<int> sta2;};void Queue::in(const int &k) {sta1.push(k);}int Queue::del(){if (sta2.empty()){while(!sta1.empty()){int tem = sta1.top();sta2.push(tem);sta1.pop();}}if (sta2.empty()) {throw runtime_error("no elements to delete!!!");}int res = sta2.top();sta2.pop();return res;}class Stack{public:public:void in(const int &k);int del();private:queue<int> que1;queue<int> que2;};void Stack::in(const int &k) {que1.push(k);}int Stack::del() {int res;if (que1.empty()){if (que2.empty())throw runtime_error("no elements to delete !!!");while(que2.size()>1){int tem = que2.front();que1.push(tem);que2.pop();}res = que2.front();que2.pop();}else {while (que1.size()>1){int tem = que1.front();que2.push(tem);que1.pop();}res = que1.front();que1.pop();}return res;}int main() {Queue test1;test1.in(3);test1.in(4);test1.del();cout << test1.del() << endl;Stack test2;test2.in(3);test2.in(4);test2.del();cout << test2.del() << endl;return 0;}
相关文章推荐
- c++实现两个堆栈模拟一个队列
- 用C++实现用两个栈实现一个队列的功能
- 两个栈来实现一个队列的C++代码
- C++之用两个栈实现一个队列
- c++ 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
- 用两个栈实现一个队列,用两个队列实现一个栈,C++ STL版
- C++两个栈实现一个队列和两个队列实现一个栈
- 《剑指Offer》附加题_用两个队列实现一个栈_C++版
- C++两个栈实现一个队列
- 利用两个队列实现一个栈(C++版)
- 用两个栈实现一个队列的功能,请用C++实现它
- 程序员面试宝典之数据结构基础----C++两个栈实现一个队列功能
- C++ 用两个栈实现一个队列
- 两个栈实现一个队列——C++ 利用STL 栈stack实现
- 剑指offer面试题java实现之题7:用两个栈模拟一个队列的入队和出队操作
- 【C++】两个队列实现一个栈
- C++两个队列实现一个栈
- 【c++】模拟实现循环队列 三种方法(标识、浪费一个空间、计数器)
- C++ 数据结构实现两个栈实现一个队列
- 两个栈来实现一个队列的C++代码