以下是某同学的成绩,通过间接寻址实现增加,删除,查询等功能
#include<iostream>
using namespace std;
# define MAX 100
class Node{
friend class List;
private:
int data;
Node* next;
};
class List{
public:
List();
List(int a[],int n);
~List();
int length();
int Get(int i);
int Locate(int x);
void Insert(int i,int x);
int Delete(int i);
void Print();
private:
Node*first,*total[MAX];
};
List::List(){
first=new Node;
first->next=NULL;
}
List::List(int a[],int n){ //头插法新建链表
if (n > MAX) throw("溢出");
Node*s;
int i;
first=new Node;
first->next=NULL;
for(i=0;i<n;i++)
{
s=new Node;
s->data=a[i];
s->next=first->next;
first->next=s;
}
}
void List::Print(){ //遍历链表
Node*p;
p=first->next;
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
}
int List::length(){ //求表长
Node*p; int count;
p=first->next;
count=0;
while(p!=NULL)
{
p=p->next;
count++;
}
return count;
}
int List::Get(int i){ //按位查找
Node*p;int count;
p=first->next;
count=1;
while(p!=NULL&&count<i)
{
p=p->next;
count++;
}
if(p==NULL) throw"位置";
else return p->data;
}
int List::Locate(int x){ //按值查找
Node*p;int count;
p=first->next;
count=1;
while(p!=NULL)
{
if(p->data==x) return count;
p=p->next;
count++;
}
return 0;
}
void List::Insert(int i,int x){ //插入
Node*p,*s;int count;
p=first;
count=0;
while(p!=NULL&&count<i-1)
{
p=p->next;
count++;
}
if(p==NULL) throw"位置";
else{
s=new Node;
s->data=x;
s->next=p->next;
p->next=s;
}
}
int List::Delete(int i) //删除
{
Node *q,*p; int x; int count;
p=first;count=0;
while(p!=NULL&&count<i-1)
{
p=p->next;
count++;
}
if(p==NULL||p->next==NULL) throw"位置";
else{
q=p->next;
x=q->data;
p->next=q->next;
delete q;
return x;
}
}
List::~List() //析构
{
Node*q;
while(first!=NULL)
{
q=first;
first=first->next;
delete q;
}
}
int main()
{
int n,i,p,num,numb,se,x,a[100];
cout<<"请输入需要创建双链表的结点个数:"<<endl;
cin>>n;
cout<<"请输入需要创建的结点:"<<endl;
for(i=0;i<n;i++)
{
cin>>a[i];
}
List student(a,n);
cout<<"打印如下: "<<endl;
student.Print();
cout<<endl<<"请输入插入结点的位置和值;"<<endl; cin>>p>>num;
student.Insert(p,num);
student.Print();
cout<<endl<<endl<<"请输入要删除结点的位置:"<<endl; cin>>numb;
cout<<"it's "<<student.Delete(numb)<<endl<<"打印链表值如下:"<<endl;
student.Print();
cout<<endl<<endl<<"请输入要查找结点的位置:"<<endl; cin>>se;
cout<<"打印链表值如下: "<<student.Get(se)<<endl;
cout<<endl<<endl<<"请输入要查找结点的数值:"<<endl; cin>>x;
cout<<"它的位置是: "<<student.Locate(x)<<endl;
return 0;
}
实验结果如图:
实验心得:
对间接寻址的特在优势还不是很明白。在本次的实验中感觉和单链表的基本操作差不多。只是多了一个结点指针数组
。所以我会找时间实验别的东西。更明显体现间接寻址的优点所在。