1 classStack {2 Public:3 //Push element x onto stack.4 voidPushintx) {5 if(Q1.empty () &&q2.empty ())6 Q1.push (x);7 Else 8 {9 if(Q1.empty ())Ten Q2.push (x); One ElseQ1.push (x); A } - - } the - //removes the element on top of the stack. - voidpop () { - if(Q1.empty () &&q2.empty ()) + return ; - Else + { A if(Q1.empty ()) at { - if(q2.size () = =1) - Q2.pop (); - Else - { - while(Q2.size () >1) in { - Q1.push (Q2.front ()); to Q2.pop (); + } - Q2.pop (); the } * } $ ElsePanax Notoginseng { - if(q1.size () = =1) the Q1.pop (); + Else A { the while(Q1.size () >1) + { - Q2.push (Q1.front ()); $ Q1.pop (); $ } - Q1.pop (); - } the } - }Wuyi } the - Wu //Get the top element. - intTop () { About if(Q1.empty () &&q2.empty ()) $ return-1; - Else - { - if(Q1.empty ()) A { + returnQ2.back (); the } - Else $ { the returnQ1.back (); the } the } the } - in the //Return Whether the stack is empty. the BOOLempty () { About if(Q1.empty () &&q2.empty ()) the return true; the Else return false; the } + Private: -queue<int>Q1; thequeue<int>Q2;Bayi};
Implement Stack using Queues