代码随想录打卡Day10|栈与队列 LeetCode232、LeetCode225

开始关于栈与队列的内容。栈是先进后出,队列是先进先出。

今天学习的内容是分别用栈实现队列和用队列实现栈。

第一题、LeetCode232 用栈实现队列 https://leetcode.cn/problems/implement-queue-using-stacks/

用一个进栈和一个出栈实现队列pop先进先出的功能。

注意要在只有stOut为空的时候,才会从stIn导入In中全部的数据,否则Out栈中顺序就错了。此外再peek中得到Out栈顶的元素后,要再把该元素压回栈中,因为peek不改变其第一个元素。

class MyQueue {
public:
    stack<int> stIn;
    stack<int> stOut;
    MyQueue() {

    }
    
    void push(int x) {
        stIn.push(x);

    }
    
    int pop() {
        //只有stOut为空的时候,才会从stIn导入数据(全部)
        if(stOut.empty()){
            while(!stIn.empty()){ //直到empty
                //从stIn导入直到in为空
                stOut.push(stIn.top());
                stIn.pop();
            }
        }
        int result = stOut.top();
        stOut.pop();
        return result;

    }
    //Get the first element
    int peek() {
        int res = this->pop();
        stOut.push(res);
        return res;//再把该元素添加回去

    }
    //return whether the stack is empty
    bool empty() {
        return stIn.empty() && stOut.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();
 */

第二题、LeetCode225、用队列实现栈 https://leetcode.cn/problems/implement-stack-using-queues/

思路类似,但用队列模拟栈不需要使用两个队列。只需要将队列的出口元素弹出再重新进入队列,直到需要的元素即可。

class MyStack {
public:
    queue<int> que;
    MyStack() {

    }
    
    void push(int x) {
        que.push(x);
    }
    
    int pop() {
        int size = que.size() - 1;
        while(size--){// 将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部
            que.push(que.front());
            que.pop();
        }
        int res = que.front();// 此时弹出的元素顺序就是栈的顺序了
        que.pop();
        return res;
    }
    
    int top() {
        return que.back();
    }
    
    bool empty() {
        return que.empty();
    }   
};

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack* obj = new MyStack();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->top();
 * bool param_4 = obj->empty();
 */

整体的方法这两道题都是差不多的。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值