My simple c++ code


  • 2
    Z

    class Stack {
    public:
    queue<int> q;

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

    };


  • 2
    T
    class Stack {
    public:
        // Push element x onto stack.
        void push(int x) {
            qu.push(x);
            back = x;
        }
    
        // Removes the element on top of the stack.
        void pop() {
            int sz = qu.size();
            if(sz == 0)
                return;
            for(int i=0;i<sz-1;i++)
            {
                back = qu.front();
                qu.pop();
                qu.push(back);
            }
            qu.pop();
        }
    
        // Get the top element.
        int top() {
            if(!qu.empty())
                return back;
            return -1;
        }
    
        // Return whether the stack is empty.
        bool empty() {
            return qu.empty();
        }
    private:
        queue<int> qu;
        int back;
    };

  • 0
    M

    method back() is not allowed!!!


Log in to reply
 

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