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;
    }
  • 相关阅读:
    [转]open channel SSD && FTL
    [转]向内核中插入虚拟块设备
    pgadmin4 python
    ssh agent-forward
    mysql中建立索引的一些原则
    cordova
    android gradle jnilibs and ant build
    minikube k8 ingress--https://kubernetes.io/docs
    kubenets installation--ranchor-mesos
    hyperledger-fabric/qemu/kvm/virtual-manager -------vagrant-virtual-box
  • 原文地址:https://www.cnblogs.com/cysolo/p/3623950.html
Copyright © 2011-2022 走看看