元素位置互換之移位算法

                                                                                          元素位置互換之移位算法

   一個長度爲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)個元素交換後的結果

Example Input

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

Example Output

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

Hint

 

注意:先將順序表元素調整爲符合要求的內容後,再做輸出,輸出過程只能在一次循環中完成,不能分成兩個部分輸出。






#include<iostream>
#include<stdlib.h>
using namespace std;
const int maxsize = 100000;
class List
{
	int data[maxsize];
public:
	int size;
	List();                        //初始化
	bool isEmpty();
	bool isFull();
	void Creat(int e);
	void Change(int m);            //元素位移
	void Print();
};
List::List()
{
	size = 0;
}
bool List:: isFull()
{
	if (size == maxsize - 1)   return true;
	else return false;
}
bool List::isEmpty()
{
	if (size == 0)   return true;
	else return false;
}
void List::Creat(int e)
{
	if (isFull())  exit(0);
	else
	{
		data[size] = e;
		size++;
	}
}
void List::Change(int m)
{
	int t;
	while (m--)
	{
		t = data[0];
		for (int i = 0; i < size - 1; i++)
			data[i] = data[i + 1];
		data[size - 1] = t;
	}
}
void List::Print()
{
	int i;
	for ( i = 0; i < size - 1; i++)
		cout << data[i] << " ";
	cout << data[size-1] << endl;
}
int main()
{
	int n; cin >> n; while (n--)
	{
		List L;
		int num, m,t;
		cin >> num >> m;
		for (int i = 0; i < num; i++)
		{
			cin >> t;
			L.Creat(t);
		}
		L.Change(m);
		L.Print();
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章