Two queue in c++


  • -1
    J
    class Stack {
    public:
    	// Push element x onto stack.
    	void push(int x) {
    		if (!que[0].empty())
    		{
    			que[0].push(x);
    		}else
    			que[1].push(x);
    	}
    
    	// Removes the element on top of the stack.
    	void pop(void) {
    		int cur = que[0].empty() ? 1 : 0;
    		while (que[cur].size() != 1)
    		{
    			que[!cur].push(que[cur].front());
    			que[cur].pop();
    		}
    		que[cur].pop();
    	}
    
    	// Get the top element.
    	int top(void) {
    		int ret = 0;
    		int cur = que[0].empty() ? 1 : 0;
    		while (que[cur].size() != 1)
    		{
    			que[!cur].push(que[cur].front());
    			que[cur].pop();
    		}
    		ret = que[cur].front();
    		que[!cur].push(ret);
    		que[cur].pop();
    		return ret;
    	}
    
    	// Return whether the stack is empty.
    	bool empty(void) {
    		return que[0].empty() && que[1].empty();
    	}
    private:
    	//queue<int> que1, que2;
    	queue<int> que[2];
    };

Log in to reply
 

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