书接上文
完整程序参考:郝斌数据结构-线性表之顺序表程序
4、从有序顺序表中删除其值在给定值s 与t之间(要求s
bool Del_s_t(struct arr *pArr,int s,int t){
int i,j;
int k;
if(s>=t||is_empty(pArr)){
return false;
} //不合理的情况退出运行
for(i=0;icnt;i++){
if(pArr->pBase[i]
k++; //记录满足条件的元素个数
}else{
break;
}
}
for(j=pArr->cnt-1;j>0;j--){//cnt-1是最有一个元素的数组下标
if(pArr->pBase[j]>t){
k++; //记录满足条件的元素个数
}else{
break;
}
}
for(;jcnt;i++,j++){
pArr->pBase[i] = pArr->pBase[j+1];//j+1的目的是将等于t的元素删掉
}
pArr->cnt = k; //将多余元素删除
return true;
}
参考答案:
bool Del_s_t_two(struct arr *pArr,int s,int t){
int i,j;
if(s>=t||pArr->cnt==0){
return false;
}
for(i=0;icnt&&pArr->pBase[i]=pArr->cnt){
return false;//检错,例如出现数组最大元素5,删除区间在5-7的情况;
}
for(j=i;jcnt&&pArr->pBase[j]<=t;j++);//j直接停在大于t的第一个元素下标上
for(;jcnt;i++,j++){
pArr->pBase[i] = pArr->pBase[j];
}
pArr->cnt=i;//脑抽了!!!i就是数组长度,无需再用k计数了。
return true;
}
5、从顺序表中删除其值在给定值s与t之间(包含s和t,要求s
不再是有序表了,首先遍历数组的全部元素,找到满足小于s和大于t的元素。用k计数,将满足条件的元素存入k的连续下标数组内。k的值就是新数组的长度。
bool Del_s_t_upgrade(struct arr *pArr,int s,int t){
int i,k=0;
if(is_empty(pArr)||s>=t){
return false;
}
for(i=0;icnt;i++){
if(pArr->pBase[i]pBase[i]>t){
pArr->pBase[k] = pArr->pBase[i];
k++;
}
}
pArr->cnt = k;
return true;
}
参考答案:
bool Del_s_t_upgrade(struct arr *pArr,int s,int t){
int i,k=0;
if(is_empty(pArr)||s>=t){
return false;
}
for(i=0;icnt;i++){
if(pArr->pBase[i]>=s||pArr->pBase[i]<=t){
k++;//记录在s和t之间的元素
}else{
pArr->pBase[i-k]=pArr->pBase[i];//将在s和t之外的元素按顺序排列
}
}
pArr->cnt -= k; //这样判断反而有点麻烦了
return true;
}



