问题描述:
现有一个栈,包含一些整型的元素,现需要将此栈从顶到底按从大到小的顺序排列(只允许申请一个新栈)。
算法实现:
public void sortStackByStack(Stack<Integer> stack) {
Stack<Integer> help = new Stack<>();
while (!stack.isEmpty()) {
int cur = stack.pop();
while (!help.isEmpty() && help.peek() < cur) {
stack.push(help.pop());
}
help.push(cur);
}
while (!help.isEmpty()) {
stack.push(help.pop());
}
}
算法解析:
1.申请一个新栈,通过这两个栈空间和栈的特性,将元素通过一定的比较规则和在两个栈中的进出栈操作,实现一个有序栈;
2.操作过程中,主要涉及到栈是否为空的判断和辅助栈中元素和待排序栈每一个将出栈元素的比较;
3.用纸笔画出两个栈,或者在大脑中构想两个栈,结合代码模拟比较和不断的进出栈操作。
原文:https://www.cnblogs.com/heibingtai/p/12637836.html