The algorithm summarizes the sorting of another stack with one stack

Source: Internet
Author: User

Use one stack to sort another stack

The type of an element in a stack is an integer, and now you want to sort the stack from top to bottom in order from large to small. Only one stack is allowed to be requested. In addition, you can apply for new variables, but cannot request additional data structures

Idea: stacks are to be sorted, and the stack of requests is recorded as help.

Perform pop operations on the stack, with the popup element recorded as Cur

If cur <= help.peek () press the CUR directly into help

If Cur>help.peek () pops up the help element, and finally pops all the elements in Help into the stack until cur is less than help.peek ()

Do this all the time until all the elements in the stack are pressed into help. Finally, all the elements in Help are pressed into the stack

Package Tt;import Java.util.stack;public class Test123 {public    static void Sortstackbystack (stack<integer> Stack) {           stack<integer> help  = new stack<integer> ();            while (!stack.isempty ()) {      int cur = stack.pop ();      while (!help.isempty () && Help.peek () <cur) {      Stack.push (Help.pop ());      }      Help.push (cur);      }    while (!help.isempty ()) {    Stack.push (Help.pop ());}}}        

  

The algorithm summarizes the sorting of another stack 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.