题目
一个栈中的元素为整型,现在想将改栈从顶到低按从大到小的顺序排序,只能申请一个栈。除此之外,可以申请新的变量,但不能申请额外的数据结构,如何完成排序
代码
public static void sortStack(Stack<Integer> stack) {
Stack<Integer> help = new Stack<>();
while (!stack.isEmpty()) {
int currentNum = stack.pop();
while (!help.isEmpty() && help.peek() > currentNum) {
stack.push(help.pop());
}
help.push(currentNum);
}
while (!help.isEmpty()) {
stack.push(help.pop());
}
}