Implement the following operations of a stack using queues.
- Push (x) –push element x onto stack.
- Pop () –removes the element on top of the stack.
- Top () –get the top element.
- Empty () –return whether the stack is empty.
Notes:
- You may assume this all operations is valid (for example, no pop or top operations would be called on an empty stack).
- Depending on your language, queue May is not supported natively. You could simulate a queue by using a list or deque (double-ended queue), as long as if you have standard operations of a Q Ueue–which means only push-to-back, pops from front, size, and is empty operations AR E valid.
Thinking of solving problems
With two queues Q1 and Q2, top () and push () operations are performed on Q1, and all elements are concentrated into Q1 before each operation.
Implementation code
//runtime:0 Ms temporarily understood as timing faultclassStack { Public://Push element x onto stack. voidPushintx) {Gather (Q1, Q2); Q1.push (x); }//Removes the element on top of the stack. voidPop () {Gather (Q1, Q2); while(Q1.size () >0&& q1.size ()! =1) {Q2.push (Q1.front ()); Q1.pop (); } q1.pop (); }//Get the top element. intTop () {Gather (Q1, Q2); while(Q1.size () >0&& q1.size ()! =1) {Q2.push (Q1.front ()); Q1.pop (); }intn = Q1.front (); Q2.push (Q1.front ()); Q1.pop ();returnN }//Return whether the stack is empty. BOOLEmpty () {returnQ1.empty () && q2.empty (); }Private: Queue<int>Q1; Queue<int>Q2;voidGather Queue<int>& Q1, Queue<int>& Q2) { while(!q2.empty ()) {Q1.push (Q2.front ()); Q2.pop (); } }};
Because a queue is empty after each push (), top (), or pop (), the Q1 is set directly to an element-aware queue. You can omit the time to enter and leave the queue.
//runtime:0 MSclassStack { Public://Push element x onto stack. voidPushintx) {toQ1 (Q1, Q2); Q1.push (x); }//Removes the element on top of the stack. voidPop () {toQ1 (Q1, Q2); while(Q1.size () >0&& q1.size ()! =1) {Q2.push (Q1.front ()); Q1.pop (); } q1.pop (); }//Get the top element. intTop () {toQ1 (Q1, Q2); while(Q1.size () >0&& q1.size ()! =1) {Q2.push (Q1.front ()); Q1.pop (); }intn = Q1.front (); Q2.push (Q1.front ()); Q1.pop ();returnN }//Return whether the stack is empty. BOOLEmpty () {returnQ1.empty () && q2.empty (); }Private: Queue<int>Q1; Queue<int>Q2;voidToQ1 ( Queue<int>& Q1, Queue<int>& Q2) {if(Q1.empty ()) {q1 = q2; Queue<int>Q q2 = q; } }};
[Leetcode] Implement Stack using Queues