leetcode用队列实现栈c++

博客主要围绕用队列实现栈展开,介绍了栈的操作,如元素入栈、移除栈顶元素、获取栈顶元素以及判断栈是否为空等,给出的解决方案是用两个队列实现栈,还提及了stl中队列的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用队列实现栈

使用队列实现栈的下列操作:

push(x) – 元素 x 入栈
pop() – 移除栈顶元素
top() – 获取栈顶元素
empty() – 返回栈是否为空


解:用两个队列实现栈

stl中队列的使用:

#include<queue>// 队列 
queue<int>  q; //参数是数据类型,这是队列的定义方式
q.empty()// 如果队列为空返回true,否则返回false  
q.size() // 返回队列中元素的个数  
q.pop()  //删除队列首元素但不返回其值  
q.front()  // 返回队首元素的值,但不删除该元素  
q.push(X) //在队尾压入新元素 ,X为要压入的元素
q.back() //返回队列尾元素的值,但不删除该元素  

class MyStack {
public:
    /** Initialize your data structure here. */
    MyStack() {
        
    }
    
    /** Push element x onto stack. */
    void push(int x) {
        input.push(x);
        q2q(output,input);
        std::swap(input,output);
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int res=output.front();
        output.pop();
        return res;
    }
    
    /** Get the top element. */
    int top() {
        return output.front();
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        return output.empty();
    }
private:
    queue<int> input;
    queue<int> output;
    void q2q(queue<int> &a,queue<int>&b)
    {
        while(!a.empty())
        {
            b.push(a.front());
            a.pop();
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陈乐乐happy

觉得对你有用的话可以打赏打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值