Topic
A stack? The type of the element is integer, and now you want to sort the stack from top to bottom in order to apply only one stack. In addition, you can apply for new variables, but you cannot request additional data structures. How do I finish sorting?
"Answer"?
1 PackageCN.HL.P4;2 3 ImportJava.util.Stack;4 5 /**6 * Title: A stack? The type of the element is integer, and now you want to sort the stack from top to bottom in order from big to small.7 * apply only one stack. In addition, you can apply for new variables, but you cannot request additional data structures. 8 * How to complete the sorting? 9 * Ten * Thought: Two stacks are given in the title, we can count the stacks to be sorted, and the auxiliary stacks as help. One * To realize that the elements in the stack are sorted from top to bottom, the order of elements in the stack should be: from small to large. A * Therefore, the elements in the help stack from top to bottom to achieve from the small to large order. So that's the key to solving the problem. - * We just need to get this right. - * the * Step: Perform pop operation on stack, the popup element is recorded as cur. - * 1. If cur is less than or equal to the top element of help, press cur directly into help. - * (!!! Keep Help from the top of the stack to the bottom of the stack in order of small to large) - * 2. If cur is greater than the top element of help (note: If the cur is pressed into help at this time, it will violate the help stack + * Top is from small to large order), then the elements of help will be ejected, pressing into the stack, until the cur is less than - * or equal to the top element of help, then press cur into help. + * 3. Repeat until all elements in the stack are pressed into help. Finally, all of the A * elements are pressed into the stack, which completes the sorting. at * - * @authorMonkey, Ko bei - * - */ - Public classDemo { - /** in * Use one stack for another stack to sort - * @paramStack to */ + Public Static voidSortstackbystack (stack<integer>stack) { - //Auxiliary Stack help thestack<integer> help =NewStack<integer>(); * //judgment. If the stack is not empty, the loop is executed. $ while(!Stack.isempty ()) {Panax Notoginseng //cur receive stack popup elements - intCur =Stack.pop (); the while(!help.isempty () && Help.peek () >cur) { + Stack.push (Help.pop ()); A } the Help.push (cur); + } - while(!Help.isempty ()) { $ Stack.push (Help.pop ()); $ } - } - the /** - * TestWuyi * @paramargs the */ - Public Static voidMain (string[] args) { WuStack S1 =NewStack (); -S1.push (5); AboutS1.push (6); $S1.push (7); - Sortstackbystack (S1); - System.out.println (S1.pop ()); - System.out.println (S1.pop ()); A System.out.println (S1.pop ()); + } the}
"Run Results"
Use one stack to sort another stack