[Leetcode] Implement Stack using Queues

Source: Internet
Author: User

Implement Stack using Queues

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 ,, pop from front , size and is empty operations is valid.

Credits:
Special thanks to @jianchao. Li.fighter for adding the problem and all test cases.

Water problem.

1 classStack {2 Private:3queue<int> que[2];4     intCur =0;5     6  Public:7     //Push element x onto stack.8     voidPushintx) {9 Que[cur].push (x);Ten     } One  A     //removes the element on top of the stack. -     voidPopvoid) { -          while(Que[cur].size () >1) { theque[1-Cur].push (Que[cur].front ()); - Que[cur].pop (); -         } - Que[cur].pop (); +Cur =1-cur; -     } +  A     //Get the top element. at     intTopvoid) { -          while(Que[cur].size () >1) { -que[1-Cur].push (Que[cur].front ()); - Que[cur].pop (); -         } -         inttop =Que[cur].front (); inque[1-Cur].push (Que[cur].front ()); - Que[cur].pop (); toCur =1-cur; +         returntop; -     } the  *     //Return Whether the stack is empty. $     BOOLEmptyvoid) {Panax Notoginseng         returnque[cur].empty (); -     } the};

[Leetcode] Implement Stack using Queues

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.