力扣-232题 用栈实现队列(C++)

该博客介绍了一种使用两个堆栈来实现队列数据结构的方法。在`MyQueue`类中,`push`操作将元素压入堆栈`stk1`,而`pop`和`peek`操作则通过将元素从`stk1`转移到`stk2`获取并移除最前面的元素。`empty`方法检查堆栈是否为空,以确定队列的状态。这种方法巧妙地利用了堆栈的特性来模拟队列的FIFO(先进先出)原则。
摘要由CSDN通过智能技术生成

题目链接:https://leetcode-cn.com/problems/implement-queue-using-stacks/
题目如下:
在这里插入图片描述
在这里插入图片描述

class MyQueue {
public:
    stack<int> stk1;
    stack<int> stk2;
    /** Initialize your data structure here. */
    MyQueue() {
        
    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        //将元素压入堆栈stk1
        stk1.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        //将元素放到stk2,拿到最先放入stk1的元素,并移除,再放回stk1
        int num;
        while(!stk1.empty()){
            num=stk1.top();
            stk1.pop();
            stk2.push(num);
        }
        num=stk2.top();
        stk2.pop();

        int num1;
        while(!stk2.empty()){
            num1=stk2.top();
            stk2.pop();
            stk1.push(num1);
        }

        return num;

    }
    
    /** Get the front element. */
    int peek() {
        //将元素依次放到stk2,拿到最后一个出栈的元素,再还原回去
        int num;
        while(!stk1.empty()){
            num=stk1.top();
            stk1.pop();
            stk2.push(num);
        }

        int num1;
        while(!stk2.empty()){
            num1=stk2.top();
            stk2.pop();
            stk1.push(num1);
        }

        return num;

    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        return stk1.empty()&&stk2.empty();
    }
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue* obj = new MyQueue();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->peek();
 * bool param_4 = obj->empty();
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值