十三:用一個棧實現另一個棧的排序

題目

請編寫一個程序, 對一個棧裏的整型數據, 按升序進行排序(即排序前, 棧裏
的數據是無序的, 排序後最大元素位於棧頂) , 要求最多隻能使用一個額外的
棧存放臨時數據, 但不得將元素複製到別的數據結構中。

實現

import java.util.Scanner;
import java.util.Stack;

public class Main {

	public static void test(Stack<Integer> stack) {
		Stack<Integer> help = new Stack<>();
		while (!stack.isEmpty()) {
			int temp = stack.pop();
			while (!help.isEmpty() && temp < help.peek()) {
				stack.push(help.pop());
			}
			help.push(temp);
		}
		
		while (!help.isEmpty()) {
			System.out.print(help.pop() + " ");
		}
	}

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		Stack<Integer> stack = new Stack<>();
		for (int i = 0; i < n; i++) {
			int temp = in.nextInt();
			stack.push(temp);
		}
		test(stack);
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章