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

来源:互联网 发布:简单心理uni 知乎 编辑:程序博客网 时间:2024/04/25 14:39

【题目】

一个栈中元素类型为整型,想将该栈从顶到底按从大到小排序,只允许申请一个栈。除此之外,可以申请新变量,但不能申请额外的数据结构。

【举例】

    public static void main(String[] args) {        Stack<Integer> ms=new Stack<Integer>();        ms.push(3);        ms.push(4);        ms.push(5);        ms.push(1);        ms.push(2);        sortStack(ms);        System.out.println(ms.pop());//5        System.out.println(ms.pop());//4        System.out.println(ms.pop());//3        System.out.println(ms.pop());//2        System.out.println(ms.pop());//1    }

【代码】

//用一个栈实现另一个栈的排序    public static void sortStack(Stack<Integer> stack){        Stack<Integer> help=new Stack<Integer>();        while(!stack.isEmpty()){            int cur=stack.pop();//已将cur弹出,准备压入help            while(!help.isEmpty()&&cur>help.peek()){                stack.push(help.pop());                //如果cur大于Help栈顶元素,将help元素逐一弹出、逐一压入stack                //直到cur小于或等于help栈顶元素,再将cur压入help            }            help.push(cur);//栈顶元素最小,cur≤栈顶,直接压入Help        }        //到这里为止,stack所有元素都弹出了        while(!help.isEmpty()){            stack.push(help.pop());//只要help不为空,将排好序的元素逐一弹出、压入到stack        }    }

【疑惑】
从结果来看,最后似乎是从顶到底按从小到大的顺序排列的?

阅读全文
0 0
原创粉丝点击