1. 程式人生 > >棧排序,只能使用額外的一個棧空間 && 有道一面

棧排序,只能使用額外的一個棧空間 && 有道一面

棧排序

題目就是棧中存的整數,對其做一個排序。哎當時沒寫出來。。。。

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;
	}
}

當輔助棧棧頂小於原棧棧頂時,把輔助棧元素一次彈回原棧直到輔助棧棧頂大於那個棧頂元素。

棧排序,只能使用額外的一個棧空間 && 有道一面