7-2 数组循环左移(20分)(顺序表实现)

题目描述:

本题要求实现一个对数组进行循环左移的简单函数:一个数组a中存有n(>0)个整数,在不允许使用另外数组的前提下,将每个整数循环向左移m(≥0)个位置,即将a中的数据由(a0 a1 … an-1)变换为(am…an-1 a0 a1…am-1)(最前面的m个数循环移至最后面的m个位置)。如果还需要考虑程序移动数据的次数尽量少,要如何设计移动的方法?

输入格式:

输入第1行给出正整数n(≤100)和整数m(≥0);第2行给出n个整数,其间以空格分隔。

输出格式:

在一行中输出循环左移m位以后的整数序列,之间用空格分隔,序列结尾不能有多余空格。

输入样例:

8 3
1 2 3 4 5 6 7 8

输出样例:

4 5 6 7 8 1 2 3

本题思路:

利用顺序表的插入、删除算法实现位移。

#include<iostream>
#include<cstdio>
#define Max 101
using namespace std ;
class Cycle
{
		int list[Max] = {0} ;
		int length ;
	public :
		Cycle( int l ) : length(l) {}  
		void Creat ()
		{
			for ( int i = 0 ; i < length ; i++ )
			{
				cin >> list[i] ;
			}
		}
		void Traverse ( int q ) 
		{
			int num = 0 ;
			while ( q-- )
			{
				int t = list[0] ;
				for ( int i = 0 ; i < length - 1 ; i++ )
				{
					list[i] = list[i+1] ;
				}
				list[length - 1] = t ;
				num++ ; 
			}
		}
		void Show ()
		{
			for(int i = 0 ; i < length ; i++ )
			{
				if ( i == 0 )    //此处加一个判断 
				cout << list[i] ;
				else 
				cout << ' ' << list[i] ;
			  } 
		}
} ; //类后加;(分号) 
int main ()
{
	int m ;  //输入长度 
	cin >> m ;
	Cycle c1( m ) ;  //返回长度 
	int n ;
	cin >> n ;
	c1.Creat() ;    //输入数组 
	c1.Traverse( n ) ;    //遍历 
	c1.Show() ;
	
	return 0 ;
}

注意:

注意:PTA上格式错误:说明输出结果与题目输出样例存在差异
数组输出时要参考英语句子输出原理,也就是第一个单词前面没有空格,或最后一个单词后面没有空格

发布了27 篇原创文章 · 获赞 16 · 访问量 1980

猜你喜欢

转载自blog.csdn.net/weixin_43899069/article/details/98311880
今日推荐