[Offoffoffer] implements queues using two stacks, and offoffoffer implements queues.

Source: Internet
Author: User

[Offoffoffer] implements queues using two stacks, and offoffoffer implements queues.
Problem description:

Use two stacks to implement a queue and complete the Push and Pop operations of the queue. The element in the queue is of the int type.

Algorithm analysis:

Push:
1. Press data into stack1;

Pop:
1. pop up all data in stack1 to stack2;
2. Set the first number in stack2 to the returned value;
3. pop up all data in stack2 to stack1;
4. Return the returned value

Code Implementation
Class Solution {public: void push (int node) {stack1.push (node) ;}int pop () {while (! Stack1.empty () {stack2.push (stack1.top (); stack1.pop ();} int node = stack2.top (); stack2.pop (); while (! Stack2.empty () {stack1.push (stack2.top (); stack2.pop ();} return node;} private: stack <int> stack1; stack <int> stack2 ;};

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.