【数据结构】将数组中的序列循环左移P个位置

思路:

step1、将R中前P个元素逆置

step2、将剩下的元素逆置

step3、将R中所有元素逆置

#include<iostream>
#define N 10
using namespace std;
void Reverse(int R[],int l,int r){//把数组倒置
    while(l<r){
        int temp;
        temp=R[l];
        R[l]=R[r];
        R[r]=temp;
        l++;
        r--;
    }
}
void shixian(int R[],int n,int p){//实现题目功能
    if(p>=n||p<=0)
        cout<<"ERROR"<<endl;
    else{
        Reverse(R,0,p-1);
        Reverse(R,p,n-1);
        Reverse(R,0,n-1);
    }
}
int main(){
    int a[N]={1,2,3,4,5,6,7,8,9,10};
    shixian(a,N,3);
    for(int i=0;i<=N-1;i++){
        cout<<a[i]<<" ";
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_34243930/article/details/79998468