用队列实现栈

问题:能否用队列实现栈?

问题分析:本质为,用队列先进先出的特性实现栈后进先出的特性。

 

 QueueToStack.h

#include <iostream>
#include "linkstack.h"
#include "LinkQueue.h"

using namespace std;
using namespace DTLib;

template <typename T>
class QueueToStack : public Stack<T>
{
protected:
    LinkQueue<T> m_queue_1;
    LinkQueue<T> m_queue_2;
    LinkQueue<T>* m_pIn;
    LinkQueue<T>* m_pOut;

    void move() const   //O(n)
    {
        int n = m_pIn->length() - 1;
        for(int i=0; i<n; i++)
        {
            m_pOut->add(m_pIn->front());
            m_pIn->remove();
        }
    }

    void swap()
    {
        LinkQueue<T>* temp = NULL;
        temp = m_pIn;
        m_pIn = m_pOut;
        m_pOut = temp;
    }
public:
    QueueToStack()
    {
        m_pIn = &m_queue_1;
        m_pOut = &m_queue_2;
    }
    void push(const T& e)  //O(1)
    {
        m_pIn->add(e);
    }
    void pop()   //O(n)
    {
        if(m_pIn->length() > 0)
        {
            move(); //转移数据元素
            m_pIn->remove();
            swap();
        }
        else
        {
            THROW_EXCEPTION(InvalidOperationException,"No element in the current queue...");
        }
    }
    T top() const   //O(n)
    {
        if(m_pIn->length() > 0)
        {
            move(); //将队列中的n-1个元素进行转移
            return m_pIn->front(); //因为已经将n-1个数据元素进行了转移,因此队列中还剩一个数据元素,即队头元素,也是最后入队列的元素。
        }
        else
        {
            THROW_EXCEPTION(InvalidOperationException,"No element in the current queue...");
        }
    }
    void clear()   //O(n)
    {
        m_queue_1.clear();
        m_queue_2.clear();
    }
    int size() const   //O(1)
    {
        return m_queue_1.length() + m_queue_2.length();
    }

};
int main()
{
    QueueToStack<int> qts;
    for(int i =0; i<10; i++)
    {
        qts.push(i);
    }

    while(qts.size() > 0)
    {
        cout << qts.top() << endl;
        qts.pop();
    }
    return 0;
}

 通过上面的打印结果,可以看出可以用队列实现栈的后进先出的特性。

栈的关键操作,时间复杂度非常差。通过这个例子仅仅是为了加强对栈和队列的理解,后进先出和先进先出是可以相互转换的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值