题解 | #用一个栈实现另一个栈的排序#
用一个栈实现另一个栈的排序
http://www.nowcoder.com/practice/ff8cba64e7894c5582deafa54cca8ff2
import java.util.Scanner;
import java.util.Stack;
public class Main {
//将栈中的元素排序
public static void sortStackByStatck(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) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Stack<Integer> stack = new Stack<Integer>();
while (n-- > 0) {
stack.push(sc.nextInt());
}
sortStackByStatck(stack);
while (!stack.isEmpty()){
System.out.print(stack.pop() + " ");//但是栈也变成一个空栈了
}
}
}

