Introduction to Algorithms 10.1-7

Source: Internet
Author: User

Title: Implement a stack with two queues and analyze the stack operation run time

Analysis:

The operation of the stack can only be done at the table header, while the queue is queued at the table head, the team can only be carried out at the end of the stack;

Consider changing the bottom element of the stack to the top of the stack, that is, you can perform a pop operation on the table header;

Solution: (without considering overflow)

1. Use two queue A with tmp,tmp queue as relay;

2, when the push operation, in queue A in the queued operation;

3, when the pop operation, so that the elements in queue a team in the queue tmp, until queue A is empty, the queue is inverted, the team head element becomes the tail element, TMP performs the team operation, the same steps in the TMP, the element is inverted into queue a

Operation Run Time Analysis:

Push:o (1)

Pop:o (N)

Introduction to Algorithms 10.1-7

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.