一个栈中元素的类型为整型,现在将该栈从栈顶到栈底按从小到大的顺序排列,只需申请一个栈,可以申请新的变量,但不能申请额外的数据结构。如何完成排序?
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 (!stack.isEmpty()) {
stack.push(help.pop());
}
}