2015-10-11 76 views
0

例如,[1,2,3,4,5]將變成[5,1,2,3,4]如何只使用指針將一個數組中的每個元素向右移動?

我不能使用額外的數組,只能使用索引遍歷。我也可以使用整數來存儲值,但這似乎沒有幫助。

這是我嘗試不工作:

void shiftonetoright(int arr[], int n){ 

    int *ptr1 = arr; 
    int s1; 

    while(n>0) 
    { 
     ptr1++; 
     s1 =*ptr1; 
     *ptr1 =s1; 

     n--; 
    } 
} 
+7

使用'的std ::旋轉(ARR,ARR + 1,ARR + N)'。 –

+0

這與你以前的問題(接受答案)有顯着不同嗎?順便說一句's1 = * ptr1; * ptr1 = s1;'在你的代碼中沒有多大意義... – Blastfurnace

+0

['std :: rotate()'](http://en.cppreference.com/w/cpp/algorithm/rotate)確實是要走的路。此外,你可能會發現Sean Parent的[C++調料](https://channel9.msdn.com/Events/GoingNative/2013/Cpp-Seasoning)在這個話題上特別提供了信息; – 865719

回答

1

你得最後一個元素轉動回到起點和簡單的移位等元素,所以有些事情更喜歡(假設n是元件在arr數):

void shiftonetoright(int arr[], int n) { 
    int last = arr[n - 1]; 
    int* ptr = arr; 
    for(int i = n - 1; i > 0; --i) { 
     *(ptr + i) = *(ptr + i - 1); 
    } 
    *ptr = last; 
} 
+3

OP [基本上在9小時前給出這個相同的代碼](http://stackoverflow.com/a/33064149/445976)。 – Blastfurnace

+0

@Blastfurnace啊,不知道那個... –

+0

這仍然是一個很好的答案,OP只是很奇怪。 – Blastfurnace

2
void shiftonetoright(int arr[], int n) 
{ 

    int *ptr1 = arr; 
    int s1 = ptr1[0]; 
    int s2; 

    for(int i = 1 ; i < n ; ++i) 
    { 
     s2 = ptr1[i]; 
     ptr1[i] = s1; 
     s1 = s2; 
    } 

    ptr1[0] = s1; 

} 
+0

Ooopss ...太多同樣的答案.... –

相關問題