实验一:顺序表

来源:互联网 发布:几个淘宝号刷一天挣40 编辑:程序博客网 时间:2024/05/22 03:19

一、实验目的

1、熟练掌握线性表的结构特点,掌握顺序表的基本操作。

2、巩固 C++相关的程序设计方法与技术。

3、学会使用顺序表解决实际问题。 

二、实验内容

1、顺序表的建立与操作实现建立 n 个元素的顺序表(n 的大小和表里数据自己确定),实现相关的操作:输出,插入,删除,查找等功能。

三、代码

由于线性表的数据元素类型不确定,所以采用C++的模板。

#include<iostream>
using namespace std;
const int MaxSize=100;
template <class DataType>
class SeqList
{
public:
SeqList(){length=0;}
SeqList(DataType a[],int n);
~SeqList(){};
int Length()
{
return length;
}
DataType Get(int i);
int Locate(DataType x);
void Insert(int i,DataType x);
DataType Delete(int i);
void PrintList();
private:
DataType data[MaxSize];
int length;
};




template<class DataType>
SeqList<DataType>::SeqList(DataType a[],int n)
{
if(n>MaxSize)throw"error";
for(int i=0;i<n;i++)
{
data[i]=a[i];
 }
length=n;
}


template<class DataType>
DataType SeqList<DataType>::Get(int i)
{
if(i<1&&i>length) throw"查找位置非法";
else return data[i-1];
}
template< class DataType>
int SeqList<DataType>::Locate(DataType x)
{
for(int i=0;i<length;i++)
if(data[i]==x)return i+1;
   return  0;
}
template<class DataType>
void SeqList<DataType>::Insert(int i,DataType x)
{
if(length>=MaxSize)throw"上溢";
if(i<1||i>length+1)throw"位置";
for(int j=length;j>=i;j--)
data[j]=data[j-1];
   data[i-1]=x;
length++;
}
template<class DataType>
DataType SeqList<DataType>::Delete(int i)
{
if(length==0)throw"下溢";
if(i<1||i>length)throw"位置";
DataType x=data[i-1];
for(int j=i;j<length;j++)
data[i-1]=data[j];
length--;
return x;
}
template<class DataType>
void SeqList<DataType>::PrintList()
{
for(int i=0;i<length;i++)
cout<<data[i];
}
int main()
{
int a[10]={2,4,5,7,8,18,25,88,99,100};
SeqList<int>l(a,10);
cout<<"所有数据如下:"<<endl;
l.PrintList();
cout<<endl;
cout<<"线性表的长度为:"<<endl<<l.Length()<<endl;
cout<<"第八位元素的值为:"<<endl;
cout<<l.Get(8)<<endl;
cout<<"查找值为25的元素位置:"<<endl;
cout<<l.Locate(25)<<endl;
cout<<"在第五个位置插入值为55的元素"<<endl;
try{l.Insert(5,55);}
catch(char*s)
{
cout<<s<<endl;
}
l.PrintList();
try{l.Delete(1);}
catch(char*s)
{
cout<<s<<endl;
}
cout<<endl<<endl;
cout<<"删除第一个元素后的全部数据为:"<<endl;
l.PrintList();
cout<<endl;
system("pause");
}






实验心得:半生不熟,上课没听,知识不懂,找着书打也输入错了很多地方,看着一堆错误,一边参照别人的,一边对着书改,终于搞定了 虽然已是凌晨。还是要提高自己的知识水平。