1. 程式人生 > >構造隊列(找規律)

構造隊列(找規律)

發現 void desc ger 一個空格 .... esc exti ()

題目描述

小明同學把1到n這n個數字按照一定的順序放入了一個隊列Q中。現在他對隊列Q執行了如下程序:
while(!Q.empty())              //隊列不空,執行循環
{
int x=Q.front(); //取出當前隊頭的值x
Q.pop(); //彈出當前隊頭
Q.push(x); //把x放入隊尾
x = Q.front(); //取出這時候隊頭的值
printf("%d\n",x); //輸出x
Q.pop(); //彈出這時候的隊頭
}
做取出隊頭的值操作的時候,並不彈出當前隊頭。
小明同學發現,這段程序恰好按順序輸出了1,2,3,...,n。現在小明想讓你構造出原始的隊列,你能做到嗎?[註:原題樣例第三行5有錯,應該為3,以下已修正]

輸入描述:

第一行一個整數T(T ≤ 100)表示數據組數,每組數據輸入一個數n(1 ≤ n ≤ 100000),輸入的所有n之和不超過200000。

輸出描述:

對於每組數據,輸出一行,表示原始的隊列。數字之間用一個空格隔開,不要在行末輸出多余的空格.
示例1

輸入

4
1
2
3
10

輸出

1
2 1
2 1 3
8 1 6 2 10 3 7 4 9 5
 1 import java.util.LinkedList;
2 import java.util.Scanner; 3 4 /** 5 * 思想:先使用一個1到n的數組模擬小明的操作, 6 * 然後會得到一組輸出,例如:3,5,10,7.... 7 * 按題意是應該輸出 1,2,3,4.... 8 * 這樣,我們就可以反推出 9 * 1應該在第3個位置 10 * 2應該在第5個位置 11 * 3應該在第10個位置 12 * 4應該在第7個位置 13 */ 14 public class Main { 15 public static void main(String[] args) { 16 Scanner scanner = new
Scanner(System.in); 17 int number = scanner.nextInt(); 18 while(number-->0){ 19 int n = scanner.nextInt(); 20 helper(n); 21 } 22 } 23 24 //模擬過程 按照題中的偽代碼 編寫 25 LinkedList<Integer> res = new LinkedList<Integer>(); 26 while (!original.isEmpty()) { 27 int x = original.removeFirst(); 28 original.addLast(x); 29 x = original.removeFirst(); 30 res.addLast(x); 31 } 32 33 //反推出正確位置,放入out數組中 34 int[] out = new int[n]; 35 for (int i = 1; i <= n; i++) { 36 int x = res.removeFirst(); 37 out[x - 1] = i; 38 } 39 40 //輸出out數組 41 System.out.print(out[0]); 42 for (int i = 1; i < n; i++) { 43 System.out.print(" "+out[i]); 44 } 45 System.out.println(); 46 } 47 }

構造隊列(找規律)