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