用一个栈实现另一个栈的排序

要求:使用一个辅助栈实现栈的排序

思路:

要排序的栈为stack,辅助栈为help

stack弹出一个元素cur,判断cur与help栈顶元素的大小,若小于或等于,则直接压入help,

否则,将help中小于cur的元素一次压入stack,之后将cur压入help,

重复上面的过程,直到stack为空。

具体代码如下:

public class pro5_sortStackByStack {
    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()) ;
        }
    }
}
原文地址:https://www.cnblogs.com/chwy/p/5619846.html