删除顺序表指定部分元素
题目
从给定顺序表中删除i~j的所有元素(包括i,j)。以顺序表:0、1、2、3、4、5、6、7、8、9、10、11为例,i取2,j取6。
#define MAXLISTSIZE 20//定义列表最大尺寸
#define LISTINCREMENT 5
#define OVERFLOW -1
#include<iostream>
#include<malloc.h>
using namespace std;
typedef int ElemType;
typedef struct{
ElemType *elem;
int length;
int listSize;
}SqList;//创建列表结构体
int InitSqList(SqList &S){
S.elem=(ElemType*)malloc(MAXLISTSIZE*sizeof(SqList));
if(!S.elem){
return OVERFLOW;
}
S.length=0;
S.listSize=MAXLISTSIZE;//队列尺寸等于分配的最大尺寸
}//定义一个列表
int CreatSqList(SqList &S){//创建一个列表并为列表赋值
for(int i=0;i<=11;i++){//通过for循环为列表赋予十一个值0-10
if(S.length>S.listSize){//若当前列表超出最大尺寸则重新给列表分配更大的空间
ElemType*newBase=(ElemType*)realloc(S.elem,(S.listSize+LISTINCREMENT)*sizeof(ElemType));
S.elem=newBase;
if(!S.elem){
return OVERFLOW;
}
}
S.length++;//列表长度加一
S.elem[i]=i;//给列表赋值
}
return 1;
}
int deleteElem(SqList &S){//删除顺序表中的元素
for(int i=7;i<=S.length;i++){
S.elem[i-5]=S.elem[i];//用7、8、9、10、11元素分别覆盖2、3、4、5、6;
}
S.length-=5;//顺序表长度减5
return 1;
}
void VisitSqList(SqList S){//访问顺序表的元素并输出
for(int i=0;i<S.length;i++){
cout<<S.elem[i]<<",";
}
cout<<endl;
}
int main(){
SqList S;//定义顺序表
InitSqList(S);//给顺序表分配空间
CreatSqList(S);//给顺序表赋值
cout<<endl;//
VisitSqList(S);//输出顺序表
deleteElem(S);//删除顺序表中的元素2-6
cout<<endl;
VisitSqList(S);//再次输出顺序表
}