如何使用两个栈模拟队列操作

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

代码如下:

#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;
}

 

posted @ 2014-03-25 19:18  源子陌  Views(728)  Comments(0Edit  收藏  举报