用两个栈实现队列 【微软面试100题 第五十七题】

题目要求:

  某队列的声明如下:

 

复制代码
   template<typename T> class CQueue
  {
   public:
    CQueue() {}
    ~CQueue() {}
    void appendTail(const T& node); // append a element to tail
    void deleteHead(); // remove a element from head
   private:
    Stack<T> m_stack1;
    Stack<T> m_stack2;
  };
复制代码

 

  用两个栈实现队列,实现appendTail()和deleteHead(),分别完成在队列尾部插入结点和在队列头部删除结点的功能。

 

 

题目分析:

  压栈的时候往stack1中压,出栈的时候,如果stack2不为空则,直接出栈stack2,如果stack2空,则把stack1的所有元素依次压入stack2,然后再出栈stack2。举个例子,如下图所示:

 

代码实现:

复制代码
#include <iostream>
#include <stack>

using namespace std;

template<class T> 
class CQueue
{
public:
    CQueue() {}
    ~CQueue() {}
    void appendTail(const T& node);
    T deleteHead();
private:
    stack<T> m_stack1;
    stack<T> m_stack2;
};
template<class T> 
void CQueue<T>::appendTail(const T& node)
{
    m_stack1.push(node);
}
template<class T> 
T CQueue<T>::deleteHead()
{
    if(m_stack2.size()==0)
    {
        while(m_stack1.size())
        {
            T data = m_stack1.top();
            m_stack1.pop();
            m_stack2.push(data);
        }
    }
    if(m_stack2.size()==0)
        throw new exception("queue is empty");
    T top = m_stack2.top();
    m_stack2.pop();

    return top;

}
int main(void)
{
    CQueue<int> queue;
    queue.appendTail(1);
    queue.appendTail(2);
    cout << queue.deleteHead()<<endl;
    queue.appendTail(3);
    cout << queue.deleteHead()<<endl;
    cout << queue.deleteHead()<<endl;

    return 0;
}
复制代码

 

posted on   tractorman  阅读(231)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?

导航

统计

点击右上角即可分享
微信分享提示