zoukankan      html  css  js  c++  java
  • 用两个栈实现队列 【微软面试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;
    }
  • 相关阅读:
    1405ST软件测试课的要求补充说明
    软测实验课安排和考试
    Asp.Net 4.0 FormAuthentication 原理
    微信支付-“申请退款”接口遇到curl出错,错误码:58
    前端资源构建-Grunt环境搭建
    微信服务号开发-获取用户位置信息
    微信支付开发-当前页面的URL未注册
    Using Redis to store php session
    nginx performance monitor
    thinkphp nginx php-fpm url rewrite 导致 404 错误
  • 原文地址:https://www.cnblogs.com/tractorman/p/4093754.html
Copyright © 2011-2022 走看看