问题及代码:
方法:
n个数往右移m格的步骤:
①把前n-m个数逆序②最后m个数逆序③所有n个数逆序。
* All rights reserved.
* 文件名称:a.cpp
* 作 者:单昕昕
* 完成日期:2016年4月19日
* 版 本 号:v1.0
* 问题描述:有n个整数,使前面各数顺序向后移动m个位置,最后m个数变成最前m个数。
* 程序输入:数据个数n,n个数据、移动位置m。
* 程序输出:移动后的数据。
*/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include <iomanip>
#include<algorithm>
using namespace std;
void mv(int a[],int n,int m)
{
int t,*p,*q;
for(p=a,q=a+n-m-1; p<q; ++p,--q)
{
t = *p;
*p = *q;
*q = t;
}
for(p=a+n-m,q=a+n-1; p<q; ++p,--q)
{
t = *p;
*p = *q;
*q = t;
}
for(p=a,q=a+n-1; p<q; ++p,--q)
{
t = *p;
*p = *q;
*q = t;
}
}
/*测试用例
10
1 2 3 4 5 6 7 8 9 10
2
*/
int main()
{
int a[80];
int m,i,n;
cin>>n;
for(i=0; i<n; i++)
cin>>a[i];
cin>>m;
mv(a,n,m);
for(i=0; i<n; i++)
cout<<a[i]<<" ";
return 0;
}
void reverse(int *a, int *b)
{
for (; a<b; a++,b--)
{
int t = *a;
*a = *b;
*b = t;
}
}
运行结果:
Note:反序函数:
void reverse(int *a, int *b)
{
for (; a<b; a++,b--)
{
int t = *a;
*a = *b;
*b = t;
}
}
void shift(int n, int *a, int m)
{
reverse(a, a+(n-m-1));
reverse(a+(n-m), a+(n-1));
reverse(a, a+(n-1));
}