一 算法思想
將順序表分成兩部分,對於元素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;
}
三 算法結果