Stacks and queues: implementing another stack's ordering with one stack

Source: Internet
Author: User

Title: The element type in a stack is integer and now wants to sort the stack from top to bottom, allowing only one stack to be requested. How do I finish sorting?

Stack the sorted stacks as help, perform pop manipulation on the stack, and eject the elements as TMP

1. If the TMP is greater than or equal to the top element of help, or it is empty, then the TMP is pressed into "help";

2. If the TMP is smaller than the top of help, eject the Help element, press the stack until TMP is greater than or equal to the top element of help, and then press TMP into help;

All the elements in the stack are pressed into help to complete the sort.

     Public Stack<integer> sortstackbystack (stack<integer> stack)    {        stacknew stack< Integer>();          while (! stack.isempty ())        {            int tmp = stack.pop ();              while (!help.isempty () && tmp < help.peek ())            {                Stack.push (Help.pop ());            }            Help.push (TMP);        }         return Help ;    }

Reference: Programmer code Interview Guide it name Enterprise algorithm and data structure problem optimal solution, Zhoecheng

Stacks and queues: implementing another stack's ordering with one stack

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.