一 概述
在一个顺序表中删除具有最小值的元素(假设唯一)并由函数返回被删除的元素的值。空出的位置由最后一个元素补充,若顺序表为空则显示出错信息并退出运行。
二 代码实现
#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;
}
三 运行结果