Implement a queue with two stacks to complete the push and pop operations of the queue. The elements in the queue are of type int.

Source: Internet
Author: User

Idea: Use Stack1 to implement the queue push operation, with Stack2 to achieve the queue of pop operations, when the Stack2 is empty, the stack1 of the data are all pressed into Stack2, waiting for the queue of pop operations.

Class solution
{public
:
    void push (int node) {
        Stack1.push (node);
    }

    int pop () {
        int result;
        if (Stack2.empty ()) {
            while (!stack1.empty ()) {
                Stack2.push (stack1.top ());
                Stack1.pop ();
            } 
        }
        result = Stack2.top ();
        Stack2.pop ();
        return result;
    }

Private:
    stack<int> stack1;
    Stack<int> stack2;
};

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.