Nine-chapter algorithm surface test 49 using stacks to implement the queue

Source: Internet
Author: User

Nine Chapters count judges Net-original website

http://www.jiuzhang.com/problem/49/


Topics

Specify that you can only use the data structure stack (support pop, push), how to use the stack to simulate a queue of pop and push?

Tip: You can use multiple stacks.

Requirements: The averaging complexity of each operation needs to be O (1)


Online test

http://lintcode.com/zh-cn/problem/implement-queue-by-stacks/


AnswerUse two stacks, stack1 and Stack2. The operation for the queue corresponds to the following:
Queue.Push:push to Stack1
Queue.pop: If Stack2 is non-null, stack2.pop otherwise pops all the numbers in the Stack1 to Stack2 (equivalent to the order upside down), then Stack2.pop ()
Each number goes in and out of Stack1 and Stack2 1 times, so the averaging complexity of two operations is O (1)

Nine-chapter algorithm surface test 49 using stacks to implement the 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.