C++用栈的方式实现队列结构

栈实现队列

使⽤栈实现队列的下列操作:
push(x) – 将⼀个元素放⼊队列的尾部。
pop() – 从队列⾸部移除元素。
peek() – 返回队列⾸部的元素。
empty() – 返回队列是否为空。

代码实现

#include<iostream>
#include<string>
#include<stack>
using namespace std;
//栈实现队列
class Myqueue
{
    public:
    //定义入栈和出栈
    stack<int> stIn;
    stack<int> stOut;
    void push(int x){
        stIn.push(x);
    }
    int pop()
    {
    	//只有出栈为空的时候才导入入栈的元素
        if(stOut.empty())
        {
            while(!stIn.empty())//全部导入
            {
                stOut.push(stIn.top());
                stIn.pop();//出栈每导入一次,入栈就弹出一次
            }
        }
        int res=stOut.top();//取出栈顶元素
        stOut.pop();//弹出栈顶元素
        return res;
    }
    int peek()
    {
        int res =this->pop();//this指针表示当对象使用peek函数时,对象可以调用公有接口pop()
        stOut.push(res);//栈顶元素在上一步被弹出,需要把它再次压入,恢复原来的出栈状态
        return res;
    }
    bool empty()
    {
        return stIn.empty()&&stOut.empty();
    }
};
int main()
{
    Myqueue queue1;
    queue1.push(1);
    queue1.push(2);
    queue1.push(3);
    queue1.peek();
    cout<<queue1.peek()<<endl;
    queue1.pop();
    queue1.peek();
    cout<<queue1.peek()<<endl;
    queue1.empty();
    cout<<queue1.empty()<<endl;
}

结果:
1
2
0

图解

pop()函数运行过程:最后实现的效果是数字1作为队列第一个进入的元素,也是队列中第一个弹出的元素,实现了队列“先进先出”的原则。peek()函数和pop类似,只不过没有把元素删除,利用pop()实现时,由于元素被弹出了,所以需要再次放进去
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值