信管117223王健数据结构实验三之间接寻址

《数据结构》实验三:

线性表综合实验

一.实验目的

巩固线性表的数据结构的存储方法和相关操作,学会针对具体应用,使用线性表的相关知识来解决具体问题。

二.实验时间

准备时间为第 7 周到第 8 周,具体集中实验时间为第 4 周第 2 次课。

2个学时。

三.实验内容

1.建立一个由 n 个学生成绩的顺序表,n 的大小由自己确定,每一个学生的成绩信息由自己确定,实现数据的对表进行插入、删除、查找等操作。分别输出结果。

要求如下:

(5)用间接寻址实现。

#include<iostream>

#include<string>

using namespace std;

const int MaxSize=100;

template<class DataType>

struct Node

{

   DataType data;

};

 template<class DataType>

 class IALink

 {

 public:

 IALink(DataType a[],int n);

     ~IALink(){};

     void Insert(int i,int x);

     int Locate(DataType x);

     DataType Delete(int i);

     void PrintList();

 private:

 Node<DataType>*address[MaxSize];

     int length;

 };  

 template<class DataType>

 IALink<DataType>::IALink(DataType a[],int n)

 {

 for(int i=0;i<n;i++)

 {

 address[i]=new Node<DataType>;

         address[i]->data=a[i];

 }

     length=n;

 }

template<class DataType>

void IALink<DataType>::Insert(int i,int x)

{

if(i<=length && i>0)

{

for(int j=length;j>=i;j--)

{

address[j]=address[j-1];

}

        address[i-1]->data=x;

        length++;

}

    else  throw"位置";

}  

template<class DataType>

DataType IALink<DataType>::Delete(int i)

{

if(i<=length && i>=0)

{

int x=address[i-1]->data;

        for(int j=i;j<length;j++)

{

address[j-1]=address[j];

}

    length--;

    return x;

}

    else  throw"位置";

}

 template<class DataType>

 int IALink<DataType>::Locate(DataType x)

 {

 for(int i=0;i<length;i++)

 {

 if(address[i]->data==x)

 return i+1;

 }

     return 0;

 }

 template<class DataType>

 void IALink<DataType>::PrintList()

 {

 for(int i=0;i<length;i++)

     cout<<address[i]->data<<" ";

 cout<<endl;

 }

int main()

{

int r[5]={100,90,80,70,60};

    IALink<int>L(r,5);

cout<<"执行插入成绩操作前数据为:"<<endl;

    L.PrintList();

    try

{

L.Insert(2,55);

}

    catch(char*s)

{

        cout<<s<<endl;

}

    cout<<"执行插入成绩操作后数据为:"<<endl;

    L.PrintList();

    cout<<"值为90的元素位置为:";

    cout<<L.Locate(74)<<endl;

    cout<<"执行删除第一个学生成绩操作前数据为:"<<endl;

    L.PrintList();

    try

{

        L.Delete(1);

}

    catch(char*s)

{

        cout<<s<<endl;

}

    cout<<"执行删除成绩操作后数据为:"<<endl;

    L.PrintList();

    return 0;

}

运行结果:

 


猜你喜欢

转载自blog.csdn.net/smart_j_king/article/details/80188220