题目:
一个栈中元素类型为整形,现在使用另外一个栈完成对该栈元素的排序,从栈顶到栈底从大到小。
解决 思路:
将要排序的栈记作 stack ,申请的辅助栈为 help 。在 stack 上执行 pop 操作 ,弹出的元素记作 cur 。
如果 cur 小于或等于 help 栈顶的元素,则将 cur 直接压入 help;
如果 cur 大于 help栈顶的元素,则将 help 中的元素逐一弹出,逐一压入到 stack 中,直到 cur 小于或者等于 help 的栈顶元素。
最后将 help 中的元素全部压到 stack 之中。
public class SortStack {
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(!help.isEmpty()){
stack.push(help.pop());
}
}
public static void main(String[] args) {
}
}
参考资料:《程序员代码面试指南》左程云 著