#include<iostream.h>
const int MaxSize=100;
struct Node
{
int data;
Node *next;
};
class Student
{
public:
Student();
Student(int a[],int n);
~Student();
void Insert(int i,int x);
static int count;
int Delete(int i);
int Get(int i);
int Locate(int x);
void Print();
private:
Node *first;
int length;
Node *address[10];
};
int Student::count=0;
Student::Student()
{
first=new Node;
first->next=NULL;
}
Student::Student(int a[],int n)
{
int i;
if(n>10) throw"溢出";
Node *s;
first=new Node;first->next=NULL;
for(i=n-1;i>=0;i--)
{
s=new Node;s->data=a[i];
s->next=first->next;first->next=s;
}
}
Student::~Student()
{
Node *q;
while(first!=NULL)
{
q=first;
first=first->next;
delete q;
}
}
void Student::Insert(int i,int x)
{
Node *p,*s;
p=first;count=0;
while(p!=NULL&&count<i-1)
{
p=p->next;
count++;
}
if(p==NULL)throw"位置非法";
s=new Node;s->data=x;
s->next=p->next;p->next=s;
length++;
}
int Student::Delete(int i)
{
int x;
Node *p,*q;
p=first;count=0;
while(p!=NULL&&count<i-1)
{
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;
}
}
int Student::Get(int i)
{
Node *p;
p=first->next;count=1;
while(p!=NULL&&count<i)
{
p=p->next;
count++;
}
if(p==NULL)throw"位置非法";
else return p->data;
}
int Student::Locate(int x)
{
Node *p;
p=first->next;count=1;
while(p!=NULL)
{
if(p->data==x) return count;
p=p->next;
count++;
}
return 0;
}
void Student::Print()
{
Node *p;
p=first->next;
while(p!=NULL)
{
cout<<p->data<<",";
p=p->next;
}
}
void main()
{
int score[5]={60,65,70,80,85};
Student S(score,5);
cout<<"学生的体育成绩:"<<endl;
S.Print();
cout<<endl<<endl<<"在位置3插入成绩75,结果如下:"<<endl;
S.Insert(3,75);
S.Print();
cout<<endl<<endl<<"在位置6删除成绩为:"<<S.Delete(6)<<endl;
cout<<"删除后结果如下:"<<endl;
S.Print();
cout<<endl<<endl<<"位置4的成绩为:"<<S.Get(4)<<endl;
cout<<endl<<endl<<"成绩65所在的位置为:"<<S.Locate(65)<<endl;
}
实验三:用间接寻址实现
最新推荐文章于 2022-05-04 11:20:44 发布