算法原理:假如要将数组循环左移i位,则先将数组前i位逆置,再将后n-i位逆置,最后将整个数组逆置。逆置也有小技巧:使用两个游标start、end,将子数组的第一个元素和子数组的最后一个元素交换,然后start++,end--。 #include<iostream> using namespace std; void reverse(char *ch,int start,int end) { while(start <= (start+end)/2) { cout<<"ch[start]="<<ch[start]<<" "<<"ch[end]"<<ch[end]<<endl; char temp; temp = ch[start]; ch[start] = ch[end]; ch[end] = temp; ++start; --end; } } int main() { char ch1[9] = "abcdefgh"; for(int t = 0;t != 8;++t) cout<<ch1[t]; cout<<endl; cout<<"你要将数组左移几位?"; int i; cin>>i; reverse(ch1,0,i-1); for(int t = 0;t != 8;++t) cout<<ch1[t]; cout<<endl; reverse(ch1,i,7); for(int t = 0;t != 8;++t) cout<<ch1[t]; cout<<endl; reverse(ch1,0,7); for(int t = 0;t != 8;++t) cout<<ch1[t]; cout<<endl; return 0; }