一 概述
在一個順序表中刪除具有最小值的元素(假設唯一)並由函數返回被刪除的元素的值。空出的位置由最後一個元素補充,若順序表爲空則顯示出錯信息並退出運行。
二 代碼實現
#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 delete_Queue(SqList &L) {
int locate = 0,last = L.length-1;
int min = L.elem[0];
for(int i = 0; i < L.length; i++) {
if(min >= L.elem[i]){
min = L.elem[i];
locate = i;
}
}
cout<<"刪除的數據爲:"<<L.elem[locate]<<endl;
L.elem[locate] = L.elem[last];
--L.length;
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:
delete_Queue(L);
cout<<"刪除後的數據序列爲:" ;
for(int i = 0; i < L.length; i++ ){
cout<<L.elem[i]<<" ";
}
cout<<endl;
break;
}
}
return 0;
}
三 運行結果