Similar to 225, the queue and stack are of the opposite nature, so they are processed at push.
Maintain two STACK:STK and TMP,STK in the opposite order of queue, such as queue: 1, 4, 5,STK: 5, 4, 1, so stk.top () will always be equal to Queue.front ().
Each push into a number x, the number of STK within the full push into the TMP, and then the X into the STK, and finally the number of TMP in the full push into STK, so that the x at the bottom of Stk.
1 classQueue {2 Public:3 //Push element x to the back of the queue.4 voidPushintx) {5 while(!Stk.empty ()) {6 Tmp.push (Stk.top ());7 Stk.pop ();8 }9 Stk.push (x);Ten while(!Tmp.empty ()) { One Stk.push (Tmp.top ()); A Tmp.pop (); - } - } the - //Removes the element from in front of the queue. - voidPopvoid) { - Stk.pop (); + } - + //Get the front element. A intPeekvoid) { at returnstk.top (); - } - - //Return Whether the queue is empty. - BOOLEmptyvoid) { - returnstk.empty (); in } - Private: tostack<int>STK, TMP; +};
Leetcode 232. Implement Queue using Stacks