【刷题实录之栈和队列】leecode232. 用栈实现队列

在这里插入图片描述
题目:请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。

实现 MyStack 类:
void push(int x) 将元素 x 压入栈顶。
int pop() 移除并返回栈顶元素。
int top() 返回栈顶元素。
boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。

题解:这是一道模拟题,不涉及到具体算法,考察的就是对栈和队列的掌握程度。使用栈来模拟队列的行为,如果仅仅用一个栈,是一定不行的,所以需要两个栈一个输入栈,一个输出栈,要注意输入栈和输出栈的关系。

代码(C++)

class MyQueue {
public:
    stack<int> stIn;
    stack<int> stOut;
    MyQueue() {
        
    }
    
    void push(int x) {
        stIn.push(x);
    }
    
    int pop() {
        int cur,res;

        while(!stIn.empty()){
            cur = stIn.top();
            stIn.pop();
            stOut.push(cur);
        }
        res = stOut.top();
        stOut.pop();
        while(!stOut.empty()){
            cur = stOut.top();
            stOut.pop();
            stIn.push(cur);
        }

        return res;
    }
    
    int peek() {
        int cur,res;

        while(!stIn.empty()){
            cur = stIn.top();
            stIn.pop();
            stOut.push(cur);
        }
        res = stOut.top();
        while(!stOut.empty()){
            cur = stOut.top();
            stOut.pop();
            stIn.push(cur);
        }

        return res;
    }
    
    bool empty() {
        return stIn.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、付费专栏及课程。

余额充值