stack 弹出元素cur,如果cur小于等于help栈顶元素,则cur压入help, cur大于help栈顶则将help的元素逐一弹出压入ctack,直到cur小于或等于help栈顶 package yf.com;import java.util.Stack;public class Main {/** * 通
package yf.com; import java.util.Stack; public class Main { /** * 通过一个栈help排序另一个栈 * @param stack 目标栈 * stack 弹出元素cur,如果cur小于等于help栈顶元素,则cur压入help, * cur大于help栈顶则将help的元素逐一弹出压入ctack,直到cur小于或等于help栈顶 */ public void sortStackByStack(Stackstack){ Stack help = new Stack (); while (!stack.isEmpty()) { int cur = stack.pop(); while (!help.isEmpty() && help.peek() < cur) { stack.push(help.pop()); } help.push(cur); } //最后将help的元素逐一压入stack while (!help.isEmpty()) { stack.push(help.pop()); } } public static void main(String[] args) { Stack stack = new Stack (); stack.push(5); stack.push(2); stack.push(4); stack.push(1); Main m = new Main(); m.sortStackByStack(stack); System.out.println(stack); } }