2
#include<iostream>
using namespace std;
/*******线性表的数据结构********/
const int defaultSize=10; //设置默认顺序表大小
template<typename DataType>
class SeqList{
private:
DataType *elements; //首地址
int maxSize; //顺序表最大大小
int length; //顺序表的有效长度
public:
//构造函数(初始化)
SeqList(int size=defaultSize){
if(size>0){
maxSize=size;
length=0;
elements=new DataType[maxSize];//分配内存大小
for(int i=0;i<maxSize;i++){
elements[i]=NULL;
}
}
}
//析构函数
~SeqList(){
delete[] elements; //回收内存空间
}
//基本操作
bool insertElement(DataType data); //在表尾插入新元素
bool deleteElement(int location); //删除指定位置的元素
DataType getElement(int location); //获取指定位置的元素
bool changeElement(int location,DataType newData);//修改指定位置处的元素值
int getLength(){//获取表长
return length;
};
} ;
//在表尾插入新元素
template<typename DataType> bool SeqList<DataType>::insertElement(DataType data){
int currentIndex=length;//记录新元素的插入位置
if(length>maxSize){
return false;//表满
}
else{
elements[currentIndex]=data;// 将新元素插入表尾
length++;//表长加1
return true;
}
}
//删除指定位置的元素
template<typename DataType> bool SeqList<DataType>::deleteElement(int location){
if(location>=length||location<0){
return false; //判断位置是否合法
}
for(int i=location;i<length;i++){
elements[i]=elements[i+1];//从location位置开始,后一个依次覆盖前一个
}
length--;//表长减1
return true;
}
//获取指定位置的元素值
template<typename DataType> DataType SeqList<DataType>::getElement(int location){
if(location>=length||location<0){
cout<<"参数无效!\n" ;
return false;//判断位置是否合法
}
return elements[location]; //返回指定元素
}
//修改指定位置的元素值
template<typename DataType>bool SeqList<DataType>::changeElement(int location,DataType newData){
if(location<0||location>=length){
cout<<"参数无效!"<<endl; //判断位置是否合法
return false;
}
elements[location]=newData; //赋值
return true;
}
//主函数
int main(){
SeqList<int> list(10); //建立顺序表
for(int i=0;i<10;i++){
list.insertElement(i*10); //插入数据实现初始化
}
//输出初始化后的顺序表
for(int i=0;i<list.getLength();i++){
cout<<list.getElement(i)<<'\t';
}
cout<<endl;
//将顺序表索引为5的元素值改为44
list.changeElement(5,44);
//输出修改后的顺序表
for(int i=0;i<list.getLength();i++){
cout<<list.getElement(i);
cout<<'\t';
}
cout<<endl;
return 0;
}