题目就是栈中存的整数,对其做一个排序。哎当时没写出来。。。。
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;
}
}当辅助栈栈顶小于原栈栈顶时,把辅助栈元素一次弹回原栈直到辅助栈栈顶大于那个栈顶元素。
原文:http://fulin0532.blog.51cto.com/6233825/1976521