题:
一个栈中元素的类型为整型,现在想将该栈从顶到底按从大到小的顺序排序,只许申请一个栈。除此之外,可以申请新的变量,但不能申请额外的数据结构。如何完成排序?
解答:
将要排序的栈标记为stack,申请的辅助栈记为help。在stack上执行pop操作,弹出的元素记为cur。
- 如果cur小于或等于help的栈顶元素,则将cur直接压入help;
- 如果cur大于help的栈顶元素,则将help元素逐一弹出,逐一压入stack,直到cur小于或等于help栈顶元素,在家cur压入help。
一直执行以上操作,直到stack中的全部元素都压入到help。最后将help中的所有元素逐一压入stack,即完成排序。
public class MyStackSort {
public static void sortStckByStack(Stack<Integer> stack){
Stack<Integer> help = new Stack<>();
while (!stack.isEmpty()){
Integer cur = stack.pop();
while (!help.isEmpty()&&help.peek()<cur){
stack.push(help.pop());
}
help.push(cur);
}
//遍历
while (!help.isEmpty()){
stack.push(help.pop());
}
}
public static void main(String[] args) {
Stack<Integer> integers = new Stack<>();
integers.push(7);
integers.push(1);
integers.push(9);
integers.push(5);
integers.push(3);
sortStckByStack(integers);
System.out.println(integers.toString());
}
}