数据结构学习C++:线性结构

线性表的插入操作:

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];
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值