Problem description: Implement a stack using two queues.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
/* 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; } } |