構造隊列問題(迴圈隊列變形java)__迴圈隊列

來源:互聯網
上載者:User

1、牛客網原題:

題目描述 小明同學把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 輸入
412310
輸出
12 12 1 38 1 6 2 10 3 7 4 9 5


2、code:已a

package schooloffer17;import java.util.Scanner;/** * Created by caoxiaohong on 17/11/5 13:27. * 小明同學把1到n這n個數字按照一定的順... * <構造隊列></構造隊列> */public class BuildQueue {    public static void main(String[] args) {        Scanner scanner=new Scanner(System.in);        int T=scanner.nextInt();        int n;        while (T-->0){            n=scanner.nextInt();            int[] numbers=new int[n];            int num=1;//插入數字            boolean isFind=false;//標識當前彈出元素前面,是否找到一個插入到隊尾的元素,只有找到,才能彈出.            for(int i=0;num<=n;i%=n){                if(isFind==false && numbers[i]==0){                    isFind=true;                    i++;                }else if(isFind==false && numbers[i]!=0){                    i++;                }else if(isFind==true && numbers[i]!=0){                    i++;                }else if(isFind==true && numbers[i]==0){                    numbers[i]=num++;                    isFind=false;                    i++;                }            }            //輸出            for(int i=0;i<n;i++){                if(i<n-1)                    System.out.print(numbers[i]+" ");                else                    System.out.println(numbers[i]);            }        }    }}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.