实验三:用间接寻址实现



#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值