本文主要是介绍数组的循环移位,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目描述:数组的循环移位。
要求:左移为负,右移为正
输入: {a,b,c},2
输出: {b,c,a}
代码:
#include <iostream>
using namespace std;
void Cycle_Mov(const char* input, int n, char* output)
{int len = strlen(input);char* temp = (char*)malloc(len*sizeof(char));int i,j;for (i = 0; i<len; i++)temp[i] = input[i];char* buff = (char*)malloc(abs(n)*sizeof(char));if (n > 0){n = n%len;for (i = 0; i < n; i++){buff[i] = temp[len - n + i];}int num = len - n;for (i = len-1; num>0; i--,num--){output[i] = temp[i - n];}for (i = 0; i < n; i++){output[i] = buff[i];}output[len] = '\0';}else if (n < 0){n = -n;n = n%len;for (i = 0; i < n; i++){buff[i] = temp[i];}for (i = 0; i < len-n; i++){output[i] = temp[i + n];}for (i = len-n,j=0; i < len; i++,j++){output[i] = buff[j];}output[len] = '\0';}
}
int main()
{char input[1000], output[1000];int i = 0;char temp = getchar();while (temp != '\n'){input[i] = temp;i++;temp = getchar();}input[i] = '\0';int n;cin >> n;Cycle_Mov(input, n, output);cout << output << endl;cin.get();cin.get();return 0;
}
这篇关于数组的循环移位的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!