Share my C++ solution,easy to understand


  • 0
    V

    int top(),simply return q.back() could also AC

       class Stack {
        public:
            queue<int> q;
            void transfer()
            {
                int n = q.size();
                int i = 0, x = 0;
                for (i = 0; i < n-1; i++)
                {
                    x = q.front();
                    q.pop();
                    q.push(x);
                }
            }
            // Push element x onto stack.
            void push(int x) {
                q.push(x);
            }
        
            // Removes the element on top of the stack.
            void pop() {
                transfer();
                q.pop();
            }
        
            // Get the top element.
            int top() {
                transfer();
                int x = q.front();
                q.pop();
                q.push(x);
        
                return x;      
            }
        
            // Return whether the stack is empty.
            bool empty() {
                return q.empty();
            }
        };

Log in to reply
 

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