两个栈模拟实现一个队列

栈的特点是后进先出,队列的特点是先进先出,所以我们用两个栈来实现,我们需要分别实现进队列和出队列,stack1进栈,然后出队列,将stack1栈顶的元素全部进入stack2,然后stack出栈,就实现了先进先出。

 

#include<iostream>

#include<stack>

using namespace std;

 

template<typename T>

class CQueue

{

public:

    CQueue(){}

    ~CQueue(){}

    void insertTail(const T &val)

    {

        stack1.push(val);        //将元素插入stack1

    }

    T deleteHead()

    {

        if (stack2.size() <= 0)       //如果stack2为空

        {

            while (!stack1.empty())      //如果stack1不为空

            {

                stack2.push(stack1.top());    //如果队列不为空,将stack1中的元素逐个插入stack2

                stack1.pop();

            }

        }

        if (stack2.size() == 0)           //如果stack2为空,队列为空

            throw new exception("queue is empty");

 

        T head = stack2.top();

        stack2.pop();

        return head;

    }

private:

    stack<T> stack1;

    stack<T> stack2;

};

 

int main()

{

    CQueue<char> queue;

    queue.insertTail('a');             //插入元素a

    queue.insertTail('b');             //插入元素b

    queue.insertTail('c');             //插入元素c

    cout << "第1次出队元素:" << queue.deleteHead() << endl;

    queue.insertTail('d');             //插入元素d

    cout << "第2次出队元素:" << queue.deleteHead() << endl;

    cout << "第3次出队元素:" << queue.deleteHead() << endl;

    cout << "第4次出队元素:" << queue.deleteHead() << endl;
    system("pause");
    return 0;

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值