One queue C++ solution slightly modified from code written by codeforlove.


  • 0
    A
    class Stack {
    public:
        // Push element x onto stack.
        void push(int x) {
            num_queue_.push(x);
        }
    
        // Removes the element on top of the stack.
        void pop(void) {                  //把队首加入队尾,同时pop
            int count = num_queue_.size() - 1;   //由于队列大小在变化,所以不能在while循环里直接使用size()
            while (count) {
                num_queue_.push(num_queue_.front());
                num_queue_.pop();
                count--;
            }
            num_queue_.pop();
        }
    
        // Get the top element.
        int top(void) {
            int count = num_queue_.size() - 1;  
            while (count) {
                num_queue_.push(num_queue_.front());
                num_queue_.pop();
                count--;
            }
            int ret = num_queue_.front();
            num_queue_.push(ret);
            num_queue_.pop();
            return ret;
        }
    
        // Return whether the stack is empty.
        bool empty(void) {
            return num_queue_.empty();
        }
    private:
        queue<int> num_queue_;
    };

Log in to reply
 

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