My c++ 0ms, very concise and simple


  • 4
    W
    class Stack {
    private:
    queue<int> q1,q2;
    public:
        // Push element x onto stack.
        void push(int x) {
            q2.push(x);
            while(!q1.empty()){
                q2.push(q1.front());
                q1.pop();
            }
            swap(q1,q2);
        }
    
        // Removes the element on top of the stack.
        void pop() {
            if(!q1.empty())
            q1.pop();
        }
    
        // Get the top element.
        int top() {
            return q1.front();
        }
    
        // Return whether the stack is empty.
        bool empty() {
            return q1.empty();
        }
    };

  • 0
    K
    class Stack {
    private:
    	queue<int> q1, q2;
    	bool del = false;
    
    	int solve(bool flag)
    	{
    		if (q1.empty())
    		{
    			int n = q2.size();
    			for (int i = 0; i < n - 1; i++)
    			{
    				q1.push(q2.front());
    				q2.pop();
    			}
    
    			if (flag == false)
    			{
    				int tmp = q2.front();
    				q1.push(q2.front());
    				q2.pop();
    				return tmp;
    			}
    			else
    			{
    				q2.pop();
    			}
    		}
    		else
    		{
    			int n = q1.size();
    			for (int i = 0; i < n - 1; i++)
    			{
    				q2.push(q1.front());
    				q1.pop();
    			}
    			if (flag == false)
    			{
    				int tmp = q1.front();
    				q2.push(q1.front());
    				q1.pop();
    				return tmp;
    			}
    			else
    			{
    				q1.pop();
    			}
    			
    		}
    	}
    
    public:
    	// Push element x onto stack.
    	void push(int x) {
    		if (!q1.empty())
    			q1.push(x);
    		else q2.push(x);
    	}
    
    	// Removes the element on top of the stack.
    	void pop() {
    		if (!empty())
    		{
    			solve(true);
    		}
    		
    	}
    
    	// Get the top element.
    	int top() {
            if (!empty())
            {
                return solve(false);
            }
    		
    	}
    
    	// Return whether the stack is empty.
    	bool empty() {
    
    		return q1.empty() && q2.empty(); 
    	}
    };

Log in to reply
 

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