排序堆栈

来源:互联网 发布:艺恩咨询数据库 编辑:程序博客网 时间:2024/06/16 06:28

题目:

给定一个堆栈,要求只用push,pop,peek以及isEmpty这四个成员函数对堆栈中的元素进行排序。

解析:

这个问题可以借助一个辅助栈来完成。排序的方法类似于插入排序,时间复杂度为O(n^2).具体细节可以参考代码。

代码:

public static Stack<Integer> sort(Stack<Integer> s) {    Stack<Integer> r = new Stack<Integer>();    while(!s.isEmpty()) {    int tmp = s.pop();    while(!r.isEmpty() && r.peek() > tmp) {     s.push(r.pop());    }    r.push(tmp);    }   return r;}