如何在时间复杂度为0(1)的情况下将顺序表L的所有元素逆置

一 算法思想

将顺序表分成两部分,对于元素L.elem[i](0 <= i < L.length/2),将其与后半部分的对应元素L.data[L.length-i-1]进行一一交换。

二 算法实现

#include<iostream>//输入头 
using namespace std;//标准输入输出

typedef int Status;
typedef int ElemType;

#define MAXSIZE 100
#define ERROR -1
#define OK 0

typedef struct {
	ElemType *elem;
	int length;
}SqList; 

Status init_Queue(SqList &L){
	
	L.elem = new ElemType[MAXSIZE]; //初始化最大长度的顺序表 
	
	if(!L.elem){
		return ERROR; //初始化失败 
	}
	
	L.length = 0; //初始时数据表为空 
	return OK;
}

Status reverse_Queue(SqList &L) {
	
	ElemType temp;
	
	for(int i = 0; i < L.length/2; i++) {
		
		temp = L.elem[i];
		L.elem[i] = L.elem[L.length-i-1];
		L.elem[L.length-i-1] = temp; 
	}
	return OK;
}

int main(){
	SqList L;
	 
	cout<<"1.初始化顺序表!\n";
	cout<<"2.输入6个不同的数字!\n";
	cout<<"3.将顺序表进行逆置!\n";
	cout<<"0.退出!"<<endl<<endl;
	
	int elect = -1;
	
	while(elect !=0){
		cout<<"请选择你的后续操作:"; 
		cin>>elect;
		switch(elect){
			case 1:
				if(!init_Queue(L)){
					cout<<"初始化顺序表成功!"<<endl; 
				}else{
					cout<<"初始化顺序表失败!"<<endl; 
				}
				break;
			case 2:
				cout<<"请输入6不同数字:" ;
				for(int i = 0; i < 6; i++){
					cin>>L.elem[i];
					L.length = 6; 
				}
				break;
			case 3:
				reverse_Queue(L);
				cout<<"逆置后的数据序列为:" ;
				for(int i = 0; i < L.length; i++ ){
				 cout<<L.elem[i]<<" ";
				} 
				cout<<endl; 
				break;
		}
	}
	return 0;
}

三 算法结果

猜你喜欢

转载自blog.csdn.net/calm_encode/article/details/106942125