PAT 1008 数组元素循环右移问题
1. 题目描述及在线测试位置
1.1 举个栗子:数组 [1,2,3,4] 循环右移一位后就变为 [4,1,2,3]。本题不允许使用另外数组协助求解,否则最后一个测试点无法通过;输出数据彼此用空格分隔,但最后一个数据后不允许有空格
1.2 在线测试位置:PAT 1008 数组元素循环右移问题
2. 具体实现
2.1 基本思路
构建双向链表定位数据元素位置,然后找到指定右移步数后的头结点,最后打印输出。
2.1.1 在接收数组数据时,模拟构建一个双向链表:pre数组用于存储当前数组元素的前一个位置、next数组用于存储当前数组元素的下一个位置
int a[number],pre[number],next[number];
for(int i=0;i<number;i++) //模拟双向链表的建立
{
cin>>a[i];
pre[i]=i-1;
next[i]=i+1;
}
head=0;
next[number-1]=0; //最后一个数组元素的下一个元素
pre[0]=number-1; //0号数组元素的上一个元素
2.1.2 数组未右移前,头地址head=0,右移一位head变成 number-1,右移两位head变为number-2,以此类推,找到右移step位数后的头地址
for(int j=0;j<step;j++)
head=pre[head]; //core code
2.1.3 知道右移后的头地址后,在next数组(标示下一个元素)的辅助下按题目要求打印即可
cout<<a[head];
for(int i=0;i<number-1;i++)
{
head=next[head];
cout<<" "<<a[head];
}
2.2 AC代码
#include <iostream>
using namespace std;
int main()
{
int number,step,head;
cin>>number>>step;
int a[number],pre[number],next[number];
step = step % number;
for(int i=0;i<number;i++) //模拟双向链表的建立
{
cin>>a[i];
pre[i]=i-1;
next[i]=i+1;
}
head=0;
next[number-1]=0;
pre[0]=number-1;
for(int j=0;j<step;j++)
head=pre[head]; //core code
cout<<a[head];
for(int i=0;i<number-1;i++)
{
head=next[head];
cout<<" "<<a[head];
}
return 0;
}