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