Simple C++ solution 0ms


  • 0
    S
    class Stack {
    public:
        // Push element x onto stack.
        void push(int x) {
            q.push(x);
            topElement = x;
        }
    
        // Removes the element on top of the stack.
        void pop() {
            int l = q.size() - 1;
            int tmp;
            while(l --){
            	tmp = q.front();
            	q.pop();
            	q.push(tmp);
            	if(l == 0) topElement = tmp; 
    		}
    		q.pop();
        }
    
        // Get the top element.
        int top() {
            return topElement;
        }
    
        // Return whether the stack is empty.
        bool empty() {
            return q.empty();
        }
        
    private:
    	queue<int> q;
    	int topElement;
    };
    

Log in to reply
 

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