C++ solution 0ms


  • 0
    B
    class Stack {
    public:
        // Push element x onto stack.
        void push(int x) {
            if (!topBuf.empty())
            {
                dataBuf.push(topBuf.front());
                topBuf.pop();
            }
    
            topBuf.push(x); 
        }
    
        // Removes the element on top of the stack.
        void pop() {
            topBuf.pop();
            if (dataBuf.size() < 1)
            {
                return;
            }
            int steps = dataBuf.size() - 1;
            while (steps > 0)
            {
                dataBuf.push(dataBuf.front());
                dataBuf.pop();
                steps--;
            }
            topBuf.push(dataBuf.front());
            dataBuf.pop(); 
        }
    
        // Get the top element.
        int top() {
            return topBuf.front();
        }
    
        // Return whether the stack is empty.
        bool empty() {
            return topBuf.empty() && dataBuf.empty();
        }
        
    private:
        queue<int> topBuf;
        queue<int> dataBuf;
    };

Log in to reply
 

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