C++实现数组循环左移(右移类似)

#include<iostream>

#define MaxSize 50
#define ElemType int
using namespace std;

typedef struct {
	ElemType data[MaxSize];
	int length;
}SqList;

void Init(SqList &L) {
	ElemType a;
	int n;  //初始的个数
	cout << "Please enter the number of elements : ";
	cin >> n;
	cout << "Please enter elements:";
	for (int i = 0; i < n; i++) {
		cin >> a;
		L.data[i] = a;
	}
	L.length = n;
}

bool Convert(SqList &L,int m,int n) { //将下标在m,n之间的数倒置
	int mid = (m + n) / 2;
	for (int i = m; i <= mid; i++) {
		swap(L.data[i], L.data[m + n - i]);  //交换位置
	}
	return true;
}

void Move_to_right(SqList &L,int p) {  //循环左移的位数p
	Convert(L, 0, p - 1);
	Convert(L, p, L.length - 1);
	Convert(L, 0, L.length - 1);
}

void Print(SqList &L) {   //输出顺序表中的元素
	int i;
	for (i = 0; i < L.length; i++) {
		cout << L.data[i] << " ";
	}
	cout << endl;
}

int main() {

	SqList L;
	Init(L);  //初始化
	Move_to_right(L, 4);
	Print(L);
	system("pause");
	return 0;
}

/*
15
1 2 2 3 3 3 4 4 4 4 5 5 5 5 5
*/


猜你喜欢

转载自blog.csdn.net/coolsunxu/article/details/80119002