C++ 0ms simple solution


  • 1
    Z
    class Queue {
    private:
    stack<int> st, tmp;
    public:
    // Push element x to the back of queue.
    void push(int x) {
        while(tmp.size()){
            st.push(tmp.top());
            tmp.pop();
        }
        st.push(x);
    }
    
    // Removes the element from in front of queue.
    void pop(void) {
        while(st.size()){
            tmp.push(st.top());
            st.pop();
        }
        tmp.pop();
    }
    
    // Get the front element.
    int peek(void) {
        while(st.size()){
            tmp.push(st.top());
            st.pop();
        }
        return tmp.top();
    }
    
    // Return whether the queue is empty.
    bool empty(void) {
        return !st.size() && !tmp.size();
    }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.