zoukankan      html  css  js  c++  java
  • 《剑指offer》第九题(用两个栈实现队列)

    // 面试题:用两个栈实现队列
    // 题目:用两个栈实现一个队列。队列的声明如下,请实现它的两个函数appendTail
    // 和deleteHead,分别完成在队列尾部插入结点和在队列头部删除结点的功能。
    
    #include <iostream>
    #include <stack>
    using namespace std;
    
    template <typename T> class CQueue//模板类,习惯就好了
    {
    private:
        stack<T> stack1;//建立两个栈
        stack<T> stack2;
    
    public:
        CQueue() {}//构造函数
        ~CQueue() {}//析构函数
    
        // 在队列末尾添加一个结点
        void appendTail(const T& node)
        {
            stack1.push(node);//就是压入第一个栈即可
        }
    
        // 删除队列的头结点
        T deleteHead()
        {
            if (stack2.size() == 0)//如果第二个栈空了
            {
                while (stack1.size() > 0)
                {
                    T& data = stack1.top();
                    stack1.pop();
                    stack2.push(data);//就一口气吧第一个栈的内容顺序弹出并压入第二个栈
                }
            }
    
            if (stack2.size() == 0)//如果上述操作后第二个栈还是空的
                throw new exception("queue is empty");//就抛出异常
    
            T head = stack2.top();//执行删除
            stack2.pop();
    
            return head;
        }
    
    };
    
    
    // ====================测试代码====================
    void Test(char actual, char expected)
    {
        if (actual == expected)
            cout << "Test passed.
    ";
        else
            cout << "Test failed.
    ";
    }
    
    int main()
    {
        CQueue<char> queue;
    
        try
        {
            queue.appendTail('a');
            queue.appendTail('b');
            queue.appendTail('c');
    
            char head = queue.deleteHead();
            Test(head, 'a');
    
            head = queue.deleteHead();
            Test(head, 'b');
    
            queue.appendTail('d');
            head = queue.deleteHead();
            Test(head, 'c');
    
            queue.appendTail('e');
            head = queue.deleteHead();
            Test(head, 'd');
    
            head = queue.deleteHead();
            Test(head, 'e');
    
            head = queue.deleteHead();
        }
        catch (...)
        {
            cout << "queue is empty.
    ";
        }
    
        system("pause");
    }

     

  • 相关阅读:
    Web 请求响应原理(转)
    openstack中的floating ip与阿里云的公网ip
    一起来说 Vim 语
    vsftpd.conf 详解与实例配置
    jquery 放大图片
    jQuery 之 .stop() 方法
    jquery 插件开发
    jquery 之效果
    jquery 之事件 多库共存(noConflict)
    测试网站是共享还是独立ip
  • 原文地址:https://www.cnblogs.com/CJT-blog/p/10467690.html
Copyright © 2011-2022 走看看