2016-12-05 163 views
-5

如何在數組中的每個元素之後插入一個新元素?如何在數組中的每個元素之後插入一個新元素?

例如,我有一個數組3,4,5,6,7,我想在每個元素後添加0。所以修改新陣列後應該是3,0,4,0,5,0,6,0,7,0

我一直在嘗試做這個過去幾個小時沒有任何成功。

謝謝大家

+3

你試過了什麼?如果我們能看到你做錯了什麼,它會更容易幫助。 –

+0

這是面試問題嗎? –

+0

*我一直試圖在過去的幾個小時內沒有任何成功。*請發佈你的嘗試。 –

回答

1

我沒有測試過這個,但它應該工作。 如果你在做這件事,那麼你需要像這樣向後工作,否則你甚至會在你讀完之前覆蓋你的一些數組。

//Make sure it has space for the zeros. 
//If we have 5 numbers here, we need space for 10 
int arr[10] = {3, 4, 5, 6, 7}; 

//Start at the last number (index 4) and work your way down. 
//If you start at zero and increment up, you will overwrite data at the beginning of the array. 
for (int i = 4; i >= 0; i--) 
{ 
    arr[i * 2] = arr[i]; //Move the number 
    arr[i * 2 + 1] = 0; //Add a zero after it 
} 
0

正如你在C中標記了它,我將在這裏避免向量。 假設您已經有10個已經分配在堆棧上的整數數組。既然你有5個元素,你需要5個零。因此得到的陣列中的總元素將爲10.

void function(int arr[], int size) 
{ 
    int loc = size/2; 
    while(size>=0) 
    { 
     if(size&1) 
      arr[size--] = arr[loc--]; 
     else 
      arr[size--] = 0; 
    } 
} 
相關問題