备战考研编程总结1——循环左移

题目描述

n个数字存入数组,将其循环左移x位,输出移动结果。

样例:

10
1 2 3 4 5 6 7 8 9 10
3
4 5 6 7 8 9 10 1 2 3 

上述是十个数字,向左移动三位,输出移动结果在最后一行。

算法

想象一个长度位n的铅笔,在长度为x的部分折成两段,即第一段长度为x,第二段长度为n-x。循环左移的x位的作用就是相当于将铅笔的第一段接在第二段后面。

具体做法就是将第一段和第二段分别掉头,再将第一段和第二段视为整体掉头,就可将铅笔的前x的长度拼接到最后。

参考代码

#include

#define maxn 105
int n;  // 数组长度

void Reverse(int a[], int b, int c){  // 将数组下标b~c的部分进行反转
    int temp;
    for(int i = b;i <= (b + c) / 2;i++){
        temp = a[i];
        a[i] = a[b+c-i];
        a[b+c-i] = temp;
    }
}

void func(int a[], int x){    // 将数组a中的元素向左循环移动x位
    Reverse(a, 0, x-1);
    Reverse(a, x, n-1);
    Reverse(a, 0, n-1);
}

int main(){
    int x;
    int a[maxn];
    scanf("%d", &n);
    for(int i = 0;i < n;i++){
        scanf("%d", a+i);
    }
    scanf("%d", &x);
    func(a, x);
    for(int i = 0;i < n;i++){
        printf("%d ", a[i]);
    }
    printf("\n");

    return 0;
}

你可能感兴趣的:(漫漫考研路,#,数据结构考研总结,c语言,算法,数据结构,考研,计算机考研)