Leetcode 232. Implement Queue using Stacks

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.