0

for example, [1,2,3,4,5] would become [5,1,2,3,4]

I cannot use an extra array and have to only use traversal by index. I can also use ints to store values, but that does not seem to help.

this is my attempt that does not work:

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

    int *ptr1 = arr;
    int s1;

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

        n--;
    }
}
watson
  • 41
  • 1
  • 7
    Use `std::rotate(arr, arr + 1, arr + n)`. – Kerrek SB Oct 11 '15 at 20:38
  • Is this significantly different from your previous question (with an accepted answer)? By the way `s1 =*ptr1; *ptr1 =s1;` in your code doesn't make much sense... – Blastfurnace Oct 11 '15 at 20:40
  • [`std::rotate()`](http://en.cppreference.com/w/cpp/algorithm/rotate) is indeed the way to go. Also, you might find Sean Parent's [C++ Seasoning](https://channel9.msdn.com/Events/GoingNative/2013/Cpp-Seasoning) talk particularly informative on this topic ;) – maddouri Oct 11 '15 at 20:44
  • @KerrekSB OP said he had to use a pointer – Paul Evans Oct 11 '15 at 20:51
  • 1
    @PaulEvans: That's fine, `arr`, `arr + 1` and `arr + n` are all pointers. – Kerrek SB Oct 11 '15 at 20:55

2 Answers2

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;

}
Titas Chanda
  • 563
  • 1
  • 4
  • 14
1

You've got to rotate the last element back to the beginning and simple shift the other elements, so some thing more like (assuming n is the number of elements in 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;
}
Paul Evans
  • 27,315
  • 3
  • 37
  • 54