代码随想录算法训练营第十天| LeetCode232 用栈实现队列、LeetCode225 用队列实现栈

232. 用栈实现队列

思路:栈具有先进后出的特点,而队列具有先进先出的特点,因此需要用两个栈来实现队列的功能,分别为stackIn和stackOut,当往队列中添加元素时,直接向stackIn中添加元素,当需要队列输出元素时,由于需要输出的元素再stackIn的底部,因此将stackIn中的所有元素输出到stackOut中,此时stackOut最外侧的元素即为需要输出的元素,注意:当stackOut不为空时直接输出,如果stackOut为空,再将stackIn全部输入。peek函数会得到队列的头元素,此时先判断stackOut是否为空,如果为空将stackIn全输入进来,然后将stackOut最外侧的元素返回。

class MyQueue {
public:
        stack<int> stackIn;
        stack<int> stackOut;
    MyQueue() {

    }
    
    void push(int x) {
        stackIn.push(x);
    }
    
    int pop() {
        int result;
        while(stackOut.empty())
        {   
            while(!stackIn.empty())
            {
            stackOut.push(stackIn.top());
            stackIn.pop();
            }
        }
        result =  stackOut.top();
        stackOut.pop();
        return result;
    }
    
    int peek() {
        int result = this->pop();
        stackOut.push(result);
        return result;
    }
    
    bool empty() {
        if(stackIn.empty()&&stackOut.empty())
        {
            return true;
        }
        else
        {
            return false;
        }
    }
};

/**
 * 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();
 */

225. 用队列实现栈

思路:栈先入后出,队列先入先出,因此栈需要输出的元素为队列尾端的元素,因此先获取队列的长度size,然后将队列的前size个元素移出,再加入到队列的尾部,此时需要输出的元素就为队列的头部,输出即可。

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

    }
    
    void push(int x) {
        q1.push(x);
    }
    
    int pop() {
        int size = q1.size();
        size--;
        while(size--)
        {
            q1.push(q1.front());
            q1.pop();
        }
        int result;
        result = q1.front();
        q1.pop();
        return result;
    }
    
    int top() {
        return   q1.back();
    }
    
    bool empty() {
        return q1.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();
 */

收获:

复习了栈和队列内部的函数,以及出入的规则。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值