zoukankan      html  css  js  c++  java
  • 如何使用两个栈模拟队列操作

    思路分析:一个为插入栈,另一个为弹出栈,可以认为插入站提供入队列的功能,弹出栈提供出队列的功能。如果弹出栈不为空,则直接弹出它的数据。如果弹出栈为空,则依次弹出插入栈的数据,放入弹出栈中,再弹出它的数据。

    代码如下:

    #include "stdafx.h"
    #include <iostream>
    #include <stack>
    using namespace std;
    template <typename T>
    class QueueByDoubleStack
    {
    public:
        size_t size();
        bool empty();
        void push(T t);
        void pop();
        T top();
    private:
        stack<T> s1;
        stack<T> s2;
    };
    template <typename T>
    size_t QueueByDoubleStack<T>::size()
    {
        return s1.size() + s2.size();
    }
    template <typename T>
    bool QueueByDoubleStack<T>::empty()
    {
        return s1.empty() && s2.empty();
    }
    template <typename T>
    void QueueByDoubleStack<T>::push(T t)
    {
        s1.push(t);
    }
    template <typename T>
    void QueueByDoubleStack<T>::pop()
    {
        if (s2.empty())
        {
            while (!s1.empty())
            {
                s2.push(s1.top());
                s1.pop();
            }
        }
        s2.pop();
    }
    template <typename T>
    T QueueByDoubleStack<T>::top()
    {
        if (s2.empty())
        {
            while (!s1.empty())
            {
                s2.push(s1.top());
                s1.top();
            }
        }
        return s2.top();
    }
    int main()
    {
        QueueByDoubleStack<int> q;
        for (int i = 0; i < 10; i++)
        {
            q.push(i);
        }
        while (!q.empty())
        {
            cout << q.top() << ' ';
            q.pop();
        }
        cout << endl;
        getchar();
        return 0;
    }
  • 相关阅读:
    settTimeout vs setInterval
    JS继承
    JS创建对象
    原型链
    开始学习python的感受
    Problem 29
    Python 查看关键字
    Problem 21
    Problem 34
    Problem 42
  • 原文地址:https://www.cnblogs.com/cysolo/p/3623950.html
Copyright © 2011-2022 走看看