Some Amazon Interview Problem Solution

Problem description: Implement a stack using two queues.

Problem link

/* The structure of the class is
class QueueStack{
private:
    queue<int> q1;
    queue<int> q2;
public:
    void push(int);
    int pop();
};
 */

/* The method push to push element into the stack */
void QueueStack :: push(int x)
{
        // Your Code
        int t;
        if(q1.size()==0 && q2.size()==0)
    	{
    		q1.push(x);
    		return;
    	}

    	if(q1.size()==0)
    	{
    		q1.push(x);
    		while(q2.size())
    		{
    			t=q2.front();
    			q2.pop();
    			q1.push(t);
    		}
    	}
    	else if(q2.size()==0)
    	{
    		q2.push(x);
    		while(q1.size())
    		{
    			t=q1.front();
    			q1.pop();
    			q2.push(t);
    		}
    	}
}

/*The method pop which return the element poped out of the stack*/
int QueueStack :: pop()
{
        // Your Code
        int t;
        if(q1.size()==0 && q2.size()==0)
    	return -1;
    	if(q1.size()==0)
    	{
    		t=q2.front();
    		q2.pop();
    		return t;
    	}
    	if(q2.size()==0)
    	{
    		t=q1.front();
    		q1.pop();
    		return t;
    	}
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *