C++ solutions using one queue for both "pop costly" and "push costly"


  • -6
    S
    // 1. O(N) pop O(1) push/top
    
    class Stack {
    public:
        // Push element x onto stack.
        void push(int x) {
            num_queue_.push(x);
            top_val_ = x;
        }
    
        // Removes the element on top of the stack.
        void pop(void) {
            int count = num_queue_.size() - 1;
            while (count) {
                top_val_ = num_queue_.front();
                num_queue_.push(top_val_);
                num_queue_.pop();
                count--;
            }
            num_queue_.pop();
        }
    
        // Get the top element.
        int top(void) {
            return top_val_;
        }
    
        // Return whether the stack is empty.
        bool empty(void) {
            return num_queue_.empty();
        }
    private:
        queue<int> num_queue_;
        int top_val_;
    };
    
    // 2. O(N) push O(1) pop/top
    
    class Stack {
    public:
        // Push element x onto stack.
        void push(int x) {
            num_queue_.push(x);
            int count = num_queue_.size() - 1;
            while (count) {
                num_queue_.push(num_queue_.front());
                num_queue_.pop();
                count--;
            }
        }
    
        // Removes the element on top of the stack.
        void pop() {
            num_queue_.pop();
        }
    
        // Get the top element.
        int top() {
            return num_queue_.front();
        }
    
        // Return whether the stack is empty.
        bool empty() {
            return num_queue_.empty();
        }
    private:
        queue<int> num_queue_;
    };

  • 0
    B

    'standard operations of a queue" - back() should not be used here.


  • 0
    S

    modified according to braydenCN's comments.


  • 0
    S

    Thanks for pointing this out.
    Modified.


Log in to reply
 

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