SDUT OJ 顺序表应用3:元素位置互换之移位算法(基于C语言)

Problem Description

一个长度为len(1<=len<=1000000)的顺序表,数据元素的类型为整型,将该表分成两半,前一半有m个元素,后一半有len-m个元素(1<=m<=len),借助元素移位的方式,设计一个空间复杂度为O(1)的算法,改变原来的顺序表,把顺序表中原来在前的m个元素放到表的后段,后len-m个元素放到表的前段。
注意:先将顺序表元素调整为符合要求的内容后,再做输出,输出过程只能用一个循环语句实现,不能分成两个部分。

Input

  第一行输入整数n,代表下面有n行输入;
之后输入n行,每行先输入整数len与整数m(分别代表本表的元素总数与前半表的元素个数),之后输入len个整数,代表对应顺序表的每个元素。

Output

  输出有n行,为每个顺序表前m个元素与后(len-m)个元素交换后的结果

Sample Input

2
10 3 1 2 3 4 5 6 7 8 9 10
5 3 10 30 20 50 80

Sample Output

4 5 6 7 8 9 10 1 2 3
50 80 10 30 20

Hint

 

注意:先将顺序表元素调整为符合要求的内容后,再做输出,输出过程只能在一次循环中完成,不能分成两个部分输出。

Source

#include<stdio.h>
#include<stdlib.h>
struct st
{
    int a[10010];
    int n;
};
int main()
{
    struct st *l,*l1;
    int i,j,T,m;
    scanf("%d",&T);
    for(j=0; j<T; j++)
    {
        l=(struct st*)malloc(sizeof(struct st));
        l1=(struct st*)malloc(sizeof(struct st));
        scanf("%d",&l->n);
        scanf("%d",&m);
        for(i=0; i<l->n; i++)
            scanf("%d",&l->a[i]);
        for(i=0; i<m; i++)
            l1->a[i]=l->a[i];
        for(i=i; i<l->n; i++)
            l->a[i-m]=l->a[i];
        for(i=i; i<l->n+m; i++)
            l->a[i-m]=l1->a[i-l->n];
        for(i=0; i<l->n-1; i++)
            printf("%d ",l->a[i]);
        printf("%d\n",l->a[i]);

    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41374539/article/details/81037074