leetcode-232. 用栈实现队列

一、题目描述

题目描述

二、思路

声明两个栈解决:
stack<int> st1用于存储;
stack<int> st2用于辅助操作。
push()实现:直接存入st1;
pop()和peak()实现:先把st1元素依次存入st2,然后获取st2的栈顶元素,操作之后将st2的元素又存入st1。

三、代码

class MyQueue {
public:
    stack<int> st1;    // 用于存储
    stack<int> st2;    // 用于辅助 
    
    /** Initialize your data structure here. */
    MyQueue() {
        
    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        st1.push(x);
        
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        while(st1.size() != 0){
            int cur = st1.top();
            st2.push(cur);
            st1.pop();
        }
        int res = st2.top();
        st2.pop();
        while(st2.size() != 0){
            int cur = st2.top();
            st1.push(cur);
            st2.pop();
        }
        return res;
    }
    
    /** Get the front element. */
    int peek() {
        while(st1.size() != 0){
            int cur = st1.top();
            st2.push(cur);
            st1.pop();
        }
        int res = st2.top();
        while(st2.size() != 0){
            int cur = st2.top();
            st1.push(cur);
            st2.pop();
        }
        return res;
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        if(st1.size() == 0)
            return true;
        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();
 */

四、提交结果

提交结果
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。