013 implementation using two stack queues (keep it up)

Source: Internet
Author: User

Implementation using two stack queues
A FIFO queue is a data structure (FIFO) that is then stacked forward out of the data structure (FILO).
The simplest way to implement two stacks is to queue up: The first push stack in a queue,
The queue pushes the first stack of data order into a second stack, and then overlays it.
Two rules:
1) into the queue, press directly into the first stack
2) out of the queue, if the second stack is not empty. Direct pop (), if the second stack is empty,

The data in the first stack is pressed into the second stack (the first stack is empty at this time).

Note that the stack is empty when actually writing the code.

Code:

#include <iostream> #include <stack>class queue{public:queue () {}~queue () {}void push (int vData) {m_ First.push (vData);} void Pop () {if (M_second.empty ()) {if (M_first.empty ()) {std::cout << "the queue is empty" << std::endl;return; }move (M_first, M_second); M_second.pop ();}} int Top () {if (M_second.empty ()) {if (M_first.empty ()) {std::cout << "the queue is empty" << Std::endl;return;} Move (M_first, M_second);} return M_second.top ();} int back () {if (M_first.empty ()) {if (M_second.empty ())} {std::cout << "the queue is empty" << std::endl;return; }move (M_second, M_first);} return M_first.top ();} Private:void Move (std::stack<int>& VL, std::stack<int>& VR) {while (!vl.empty ()) {Vr.push (VL.top ( )); Vl.pop ();}} Private:std::stack<int> m_first;std::stack<int> M_second;};


Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.

013 implementation uses two stack queues (keep it up)

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.