首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

面试题:用两个栈实现一个队列的功能?请用C++实现之解决方案

2012-04-02 
面试题:用两个栈实现一个队列的功能?请用C++实现之面试题:用两个栈实现一个队列的功能?请用C++实现之思路:

面试题:用两个栈实现一个队列的功能?请用C++实现之
面试题:

  用两个栈实现一个队列的功能?请用C++实现之

思路:

  假设两个栈 A 和B,且都为空。
  可以认为栈 A 为提供入队列的功能,栈 B 提供出队列的功能。
  入队列: 入栈 A 
  出队列:
  1 如果栈B 不为空,直接弹出栈 B 的数据。
  2 如果栈 B 为空,则依次弹出栈 A 的数据,放入栈 B 中,再弹出栈 B 的数据。



[解决办法]

C/C++ code
#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;} 

热点排行