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

来源:互联网 发布:数据治理 权威定义 编辑:程序博客网 时间:2024/03/28 20:15

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

代码如下:

package chapter1;import java.util.Stack;public class sortStackByStack {    public static void main(String []args){    Stack<Integer> st = new Stack<Integer>() ;    st.push(3) ;    st.push(2) ;    st.push(1) ;    st.push(5) ;    st.push(4) ;    sortStack(st) ;    while(!st.isEmpty())    System.out.println(st.pop());    }    public static void sortStack(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());    }    }}


0 0