面试题:用两个栈实现一个队列的功能?请用C++实现之
面试题:
用两个栈实现一个队列的功能?请用C++实现之
思路:
假设两个栈 A 和B,且都为空。
可以认为栈 A 为提供入队列的功能,栈 B 提供出队列的功能。
入队列: 入栈 A
出队列:
1 如果栈B 不为空,直接弹出栈 B 的数据。
2 如果栈 B 为空,则依次弹出栈 A 的数据,放入栈 B 中,再弹出栈 B 的数据。
[解决办法]
#include <iostream>#include <stack>using namespace std;template<class T>struct MyQueue{ void push(T &t) { s1.push(t); } T front() { if(s2.empty()) { if(s1.size() == 0) throw; while(!s1.empty()) { s2.push(s1.top()); s1.pop(); } } return s2.top(); } void pop() { if(s2.empty()) { while(!s1.empty()) { s2.push(s1.top()); s1.pop(); } } if(!s2.empty()) s2.pop(); } stack<T> s1; stack<T> s2;};int main(){ MyQueue<int> mq; for(int i=0; i< 10; ++i) { mq.push(i); } for(i=0; i< 12; ++i) { cout<<mq.front()<<endl; mq.pop(); } return 0;}