"Sword means offer" with two stacks to implement a queue

Source: Internet
Author: User

Problem Description:

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.

Algorithm Analysis:

Push
1. Press the data into the STACK1;

Pop
1. Eject all data from the stack1 to Stack2;
2. Set the first number in the Stack2 to the return value;
3. Eject all data from the Stack2 to Stack1;
4. Return the return value

Code implementation
classsolution{ Public:voidPushintnode) {Stack1.push (node); }intPop () { while(!stack1.empty ())            {Stack2.push (Stack1.top ());        Stack1.pop (); }intnode = Stack2.top (); Stack2.pop (); while(!stack2.empty ())            {Stack1.push (Stack2.top ());        Stack2.pop (); }returnNode }Private: Stack<int>Stack1; Stack<int>Stack2;};

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Sword means offer" with 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.