线性表的插入操作:
1.首先在插入数据之前是要先判断一下数组已满和查找下标是否合法
2.在指定位置i插入数据x,原来就是将下标为i与i后面的数据向后移
3.i位置已经腾出来,此时将x插入
代码如下
template <class DataType>
void SeqList<DataType>::Insert(DataType x,int i){
if(len >= MaxSize) throw "Overflow";
if(i <1 ||i>len+1) throw "Location";
for(int j=len;j>=i;j--){
data[j]=data[j-1];
}
data[i-1]=x;
len++;
}
删除操作
1.删除下标为i的数据,将下标i之后的所以数据都向前移动一位,这样i的数据就会被i+1的数据给覆盖
2.将数组的长度减1
代码如下:
template <class DataType>
DataType SeqList<DataType>::Delete(int i){
if(len == 0) throw "underflow";
if(i<1 || i>len) throw "location";
DataType temp = data[i];
for(int j=i;j<=len;j++){
data[j-1]=data[j];
}
len--;
return temp;
}
所有代码如下(仅供参考)
template <class DataType>
class SeqList{
private:
DataType data[MaxSize];
int len;
public:
SeqList(){len=0;}
SeqList(DataType a[],int n);
int Length(){return len;}
void Insert(DataType x,int i);//在位置为i的位置插入x
DataType Delete(int i);//删除i位置
void display();//显示数据
DataType Get(int i);
int IndexOf(DataType x);
};
template <class DataType>
SeqList<DataType>::SeqList(DataType a[],int n){
if(n>MaxSize) throw "overflow";
for(int i=0;i<n;i++){
data[i] = a[i];
}
len = n;
}
template <class DataType>
void SeqList<DataType>::Insert(DataType x,int i){
if(len >= MaxSize) throw "Overflow";
if(i <1 ||i>len+1) throw "Location";
for(int j=len;j>=i;j--){
data[j]=data[j-1];
}
data[i-1]=x;
len++;
}
template <class DataType>
void SeqList<DataType>::display(){
cout << "节点有:"<<endl;
for(int i=0;i<len;i++){
cout <<data[i] <<" ";
}
}
template <class DataType>
DataType SeqList<DataType>::Delete(int i){
if(len == 0) throw "underflow";
if(i<1 || i>len) throw "location";
DataType temp = data[i];
for(int j=i;j<=len;j++){
data[j-1]=data[j];
}
len--;
return temp;
}
template <class DataType>
int SeqList<DataType>::IndexOf(DataType x){
for(int i=0;i<len;i++){
if(data[i] == x){
return i+1;
}
}
return -1;
}
template <class DataType>
DataType SeqList<DataType>::Get(int i){
if(i<1 || i>len){
return -1;
}
return data[i-1];
}