您的位置:首页 > 其它

用两个栈实现一个队列功能

2015-11-05 01:46 549 查看
#include<iostream>
#include<stack>
using namespace
std;

/*使用两个堆栈实现队列
 s1:实现入队,s2:实现出队
 首先,将数据存放在栈s1中,然后将数据push进s2中,再将s2中的数据pop
 出队列:
 (1)如果栈B不为空,直接弹出栈B的数据
 (2)如果栈B为空,则依次弹出栈A的数据,放入栈B中,再弹出栈B的数据
 */
template<class T>

struct Queue
{
    stack<T> s1;
    stack<T> s2;
    
    //s1入栈一个元素
    void push(T &t)
    {
        s1.push(t);
    }
    
    //取出s2栈顶的元素,并移除。
    T front()
    {
        if(s2.empty())
        {
            if(s1.size()==0)
                throw;
            while(!s1.empty())
            {
                s2.push(s1.top());
               
s1.pop(); //取出不要漏掉移除栈顶元素
            }
        }
        
        int value =
s2.top();
        s2.pop();
        return value;
    }
    
    //把s1的内容倒入s2中
    void pop()
    {
        if(s2.empty())
        {
            while(!s1.empty())
            {
                s2.push(s1.top());
                s1.pop();
            }
        }
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: