题目:
设计一个顺序表类,实现类中的基本操作(构造函数、删除、插入、按位置查找、按值查找、输出顺序表)。
实验内容
1、建立一个顺序表L={21,23,16,45,65,17,31,9},输出该表中各元素的值;
2、在顺序表L中第i=4的位置插入元素68;
3、删除顺序表L中第i=7的数据元素,并输出被删除的元素值;
4、输出顺序表L中所有元素。
代码:
#include <iostream>
using namespace std;
const int MaxSize=100;
template<class DataType>
class SeqList
{
public:
SeqList(){length=0;} //构造函数,初始化顺序表,令表的长度为0
SeqList(int Array[],int n);//构造函数,给顺序表赋值
~SeqList(){}
void Insert(int i,DataType x); //插入函数,在i位置插入数据值为x的元素
DataType Delete(int i); //删除函数,删除i位置的元素
DataType Get(int i); //按位查找函数,查找i位置的元素
int Locate(DataType x); //按值查找,查找数据值为x的在表中的位置
void Print(); //输出顺序表的元素
private:
int length; //顺序表的长度
DataType data[MaxSize]; //用数组保存顺序表的元素
};
template<class DataType>---------//有璨构造函数
SeqList<DataType>::SeqList(int Array[],int n)
{
int i;
for(i=0;i<n;i++)
data[i]=Array[i];
length=n;
}
template<class DataType>----------//顺序表插入
void SeqList<DataType>::Insert(int i,DataType x)------//i->位置,x->插入的元素
{
if(length>=MaxSize) throw "顺序表已满,插入出错。";
if(i<0||i>length+1) throw "插入位置有误。";
int j;
for(j=length;j>=i;j--)
data[j]=data[j-1]; //注意第j个元素存在于数组下标为j-1处
data[i-1]=x;
length++;
}
template<class DataType>------------//顺序表删除
DataType SeqList<DataType>::Delete(int i)
{
if(i<0||i>length) throw "删除位置有误。";
if(length==0) throw "顺序表已空,不能删除。";
DataType x;
int j;
x=data[i-1];
for(j=i;j<length;j++)
data[j-1]=data[j];
length--;
return x;
}
template<class DataType>---------------//顺序表按位查找
DataType SeqList<DataType>::Get(int i)
{
if(i<0||i>length) throw "位置有误。";
return data[i-1];
}
template<class DataType>----------------//顺序表按值查找
int SeqList<DataType>::Locate(DataType x)
{
int i;
for(i=0;i<length;i++)
{
if(data[i]==x)
return i+1;
}
return -1;
}
template<class DataType>----------//顺序表遍历
void SeqList<DataType>::Print()
{
int i;
if(length==0) throw "表已空。";
for(i=0;i<length;i++)
cout<<data[i]<<" "; //依次输出线性表的元素值
cout<<"\n";
}
int main()
{
int array[8]={21,23,16,45,65,17,31,9};
SeqList<int> List(array,8);
cout<<"初始化顺序表,并输出表中各元素的值\n";
List.Print();
cout<<"在i=4位置插入元素68\n";
List.Insert(4,68);
cout<<"输出插入之后的表的各元素的值\n";
List.Print();
cout<<"输出删除的元素\n";
cout<<List.Delete(7)<<"\n";
cout<<"输出删除元素之后的表的各元素的值\n";
List.Print();
return 0;
}