Leetcode Implement Stack using Queues

Source: Internet
Author: User

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 must the only standard operations of a queue – which means only push to back ,, peek/pop from front size , and is empty operations AR E valid.
      • 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.
      • You may assume this all operations is valid (for example, no pop or top operations would be called on an empty stack).
classStack {Private: Queue<int> que[2]; intCurrent ; voidTransfer (queue<int>& que1, queue<int>& Que2,intN) { for(intI=0; i<n; i++) {Que2.push (Que1.front ());        Que1.pop (); }    }  Public: Stack (): Current (0){}    //Push element x onto stack.    voidPushintx) {que[current].push (x); }    //removes the element on top of the stack.    voidpop () {intNums =que[current].size (); if(Nums = =0) {            return; } transfer (Que[current], que[1-current], nums-1);        Que[current].pop (); Current=1-Current ; }    //Get the top element.    intTop () {if(Empty ()) {return 0; }        returnQue[current].back (); }    //Return Whether the stack is empty.    BOOLempty () {returnQue[current].empty (); }};

You can also use a queue to complete, but for the queue one and two are no different than just a pointer.

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.