题目就是栈中存的整数,对其做一个排序。哎当时没写出来。。。。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
import java.util.Stack;
public class 栈排序 {
public static void main(String[] args) {
Stack<Integer> s = new Stack<Integer>();
s.push( 4 );
s.push( 6 );
s.push( 1 );
s.push( 3 );
s.push( 2 );
// while(!s.isEmpty()){ // System.out.println("排序前"); // System.out.println(s.pop()); // } s = sort(s);
while (!s.isEmpty()){
//System.out.println("排序后");
System.out.println(s.pop());
}
}
public static Stack<Integer> sort(Stack<Integer> s){
Stack<Integer> ret = new Stack<Integer>();
while (!s.isEmpty()){
int top = s.pop();
while (!ret.isEmpty() && ret.peek() < top){
s.push(ret.pop());
}
ret.push(top);
}
return ret;
}
} |
当辅助栈栈顶小于原栈栈顶时,把辅助栈元素一次弹回原栈直到辅助栈栈顶大于那个栈顶元素。
本文转自 努力的C 51CTO博客,原文链接:http://blog.51cto.com/fulin0532/1976521