Tried to do this problem 2 months ago, didn't understand it back then, now I think I do, C++ 0ms using one queue


  • 0
    K
    class Stack {
    public:
        // Push element x onto stack.
        std::queue<int> queue;
        int count;
        void push(int x) {
            queue.push(x);
        }
    
        // Removes the element on top of the stack.
        void pop() {
            count = 0;
            while(queue.size() - 1 > count)
            {
                queue.push(queue.front());
                queue.pop();
                count++;
            }
            queue.pop();
        }
    
        // Get the top element.
        int top() {
            return queue.back();
        }
    
        // Return whether the stack is empty.
        bool empty() {
            return queue.empty();
        }
    };

  • 0

    you can not use queue.back()


  • 0
    K

    Sorry I didn't read the question through, I will go ahead and close this thread.


Log in to reply
 

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