分析:
就像模拟放圆盘一样,当大盘子不能放到小盘子上,若盘子太大不能放,就把小盘子放回,大盘子拿着找到合适的位置再放
import java.util.Stack;
public class Main {
public static int numbers[] = {1,2,31,312,12,9};
public static void main(String[] args) {
Stack<Integer> st = new Stack<>();
int nl = numbers.length;
for(int i = 0; i <nl; i ++) {
st.push(numbers[i]);
}
System.out.println(st);
//开始排序
Stack<Integer> stt = new Stack<>();
while(!st.isEmpty()) {
int t = st.pop();
if(stt.isEmpty()) {
stt.push(t);
}
else {
while(!stt.isEmpty() && t > stt.peek()) {
int t3 = stt.pop();
st.push(t3);
}
stt.push(t);
}
}
System.out.println(stt);
}
}
运行结果:
[1, 2, 31, 312, 12, 9]
[312, 31, 12, 9, 2, 1]