題目
一個棧中的元素爲整型,現在想將改棧從頂到低按從大到小的順序排序,只能申請一個棧。除此之外,可以申請新的變量,但不能申請額外的數據結構,如何完成排序
代碼
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());
}
}