间接寻址

来源:互联网 发布:算法有哪些 编辑:程序博客网 时间:2024/04/27 16:11

间接寻址

一、实验目的

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

二、实验内容

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

三、详细设计(C++)

1.算法设计

定义顺序表的数据类型——间接寻址类,包括插入、删除、查找、遍历等基本操作。

间接寻址是将数组和指针结合起来的一种方法,它将数组中存储数据元素的单元改为存储指向该元素的指针。

查找操作:

1.从第一位开始依次查找与x值相同的元素;

2.找到即输出下标为i的元素的序号i+1;

插入操作:

1.如果元素的插入位置不合理,则抛出位置非法;

2.将最后一个元素直至第i个元素分别向后移动一个位置;

3.将元素x填入位置i处;

4.表长加1。

删除操作:

1.如果表空,则抛出下溢异常;

2.如果删除位置不合理,则抛出位置非法;

3.取出被删除元素;

4.将下标为i,i+1,…,n-1处的元素分别移到下标i-1,i,…,n-2处;

5.表长减1,返回被删除值。

2.源程序代码

#include<iostream>using namespace std;const int MaxSize=100;struct Node{int data;};class IndirectList{public:IndirectList();IndirectList(int a[],int n);~IndirectList();int Locate(int x);void Insert(int i,int x);int Delete(int i);void PrintList();private:Node *data[MaxSize];int length;};IndirectList::IndirectList(){for(int i=0;i<MaxSize-1;i++){data[i]=NULL;}length=0;}IndirectList::IndirectList(int a[],int n){if(n<0||n>MaxSize)throw"参数非法";for(int i=0;i<MaxSize;i++){data[i]=NULL;}for(int j=0;j<n;j++){data[j]=new Node;data[j]->data=a[j];}length=n;}IndirectList::~IndirectList(){Node *p;for(int i=0;i<length;i++){p=data[i];data[i]=NULL;delete p;}}int IndirectList::Locate(int x){for(int i=0;i<length;i++)if(data[i]->data==x) return i+1;return 0;}void IndirectList::Insert(int i,int x){if(i<1||i>length+1)throw"位置非法";for(int j=length;j>=i;j--)data[j]=data[j-1];data[i-1]=new Node;data[i-1]->data=x;length++;}int IndirectList::Delete(int i){if(length==0)throw"下溢异常";if(i<1||i>length)throw"位置非法";Node *p=data[i-1];int x=p->data;for(int j=i-1;j<length-1;j++)data[j]=data[j+1];delete p;length--;data[length]=NULL;return x;}void IndirectList::PrintList(){for(int i=0;i<length;i++)cout<<data[i]->data<<" ";cout<<endl;}void main(){int score[10]={95,64,78,59,46,39,66,89,91,10};IndirectList List(score,10);cout<<"查询分数前的数据为:"<<endl;List.PrintList();cout<<"值为66的元素位置为:";cout<<List.Locate(66)<<endl;cout<<"插入前的数据为:"<<endl;List.PrintList();try{List.Insert(2,77);}catch(char *s){cout<<s<<endl;}cout<<"插入后的数据为:"<<endl;List.PrintList();cout<<"删除前的数据为:"<<endl;List.PrintList();try{List.Delete(10);}catch(char *s){cout<<s<<endl;}cout<<"删除第十个元素后的数据为:"<<endl;    List.PrintList();system("pause");}

四、运行与测试结果