Using two stacks to implement a queue

Source: Internet
Author: User

Topic description Use two stacks to implement a queue, complete the queue push and pop operations.  The elements in the queue are of type int. Tips:

Two stacks to implement a queue function? Ask for the algorithm and ideas!

< analysis;:

Queue: Put elements into Stack a

Out team: Determine if stack B is empty, if it is empty, then all elements of stack a POPs, and push into stack B, stack b out of the stack;

If not empty, stack B is directly out of the stack.

The ability to implement a stack with two queues? Ask for the algorithm and ideas!

< analysis;:

Into the stack: put elements into queue a

Stack: Determine whether the number of elements in queue A is 1, if equal to 1, or out of the queue, otherwise, the elements in queue a out of the queue and put in queue B, until one of the remaining elements in queue A, and then queue a out of the queue, and then put the elements in queue B out of queue a queue a.

Solution 1:
classsolution{ Public:    voidPushintnode)    {Stack1.push (node); }    intpop () {if(Stack2.empty ()) { while(!Stack1.empty ()) {                inttemp =Stack1.top ();                Stack1.pop ();            Stack2.push (temp); }        }        intresult =Stack2.top ();        Stack2.pop (); returnresult; }Private: Stack<int>Stack1; Stack<int>Stack2;};
Solution 2:

Using two stacks to implement a queue

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.