如有元素个数为n的序列: abcdefgh 要求循环左移 p位(如设置p=3),则要求操作后的序列从 abcdefgh 变为: defghabc
把 abc 设为序列A,defgh设为序列B
先将 A 逆置得到 cba
再将 B 逆置得到 hgfed
得到 cbahgfed
再整个序列逆置一次即得到 defghabc 即BA
这是有公式的:
逆置代码:
void Reverse(ElemType A[],int left,int right) { int i =0; for(i; i<(right - left + 1)/2 ; i++) { //交换 ElemType temp; temp = A[left+i]; A[left+i] = A[right-i]; A[right-i] = A[left+i]; } } 要实现左移,如上图分三步走,实现三次逆置即可实现代码:
void Reverse(ElemType A[],int left,int right) { int i =0; for(i; i<(right - left + 1)/2 ; i++) { //交换 ElemType temp; temp = A[left+i]; A[left+i] = A[right-i]; A[right-i] = A[left+i]; } } void func(ElemType A[]) { Reverse(A[],0,p-1);//前部分序列逆置 Reverse(A[],p,n-1);//后部分序列逆置 Reverse(A[],0,n-1);//整个序列逆置 }