一、左旋
/* Function to left rotate arr[] of size n by d */
void leftRotate(int arr[], int d, int n)
{
rvereseArray(arr, 0, d-1);
rvereseArray(arr, d, n-1);
rvereseArray(arr, 0, n-1);
}
/*Function to reverse arr[] from index start to end*/
void rvereseArray(int arr[], int start, int end)
{
int i;
int temp;
while(start < end)
{
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
二、右旋
/* Function to right rotate arr[] of size n by d */
void rightRotate(int arr[], int d, int n)
{
rvereseArray(arr, 0, n-d-1);
rvereseArray(arr, n-d, n-1);
rvereseArray(arr, 0, n-1);
}
或者/* Function to right rotate arr[] of size n by d */
void rightRotate(int arr[], int d, int n)
{
d = n-d;
rvereseArray(arr, 0, d-1);
rvereseArray(arr, d, n-1);
rvereseArray(arr, 0, n-1);
}
对于字符串,左旋如下:
char * invert(char *start, char *end)
{
char tmp, *ptmp = start;
while (start != NULL && end != NULL && start < end)
{
tmp = *start;
*start = *end;
*end = tmp;
start ++;
end --;
}
return ptmp;
}
char *left(char *s, int pos) //pos为要旋转的字符个数,或长度,下面主函数测试中,pos=3。
{
int len = strlen(s);
invert(s, s + (pos - 1)); //如上,X->X^T,即 abc->cba
invert(s + pos, s + (len - 1)); //如上,Y->Y^T,即 def->fed
invert(s, s + (len - 1)); //如上,整个翻转,(X^TY^T)^T=YX,即 cbafed->defabc。
return s;
}