#include<iostream.h>
struct Node
{
intdata;
Node*next;
};
class Student
{
public:
Student();
Student(inta[],int n);
~Student();
voidInsert(int i,int x);
staticint count;
intDelete(int i);
intGet(int i);
intLocate(int x);
voidPrint();
private:
Node*first;
};
int Student::count=0;
Student::Student()
{
first=newNode;
first->next=NULL;
}
Student::Student(int a[],int n)
{
inti;
Node*s;
first=newNode;first->next=NULL;
for(i=0;i<n;i++)
{
s=newNode;s->data=a[i];
s->next=first->next;first->next=s;
}
}
Student::~Student()
{
Node*q;
while(first!=NULL)
{
q=first;
first=first->next;
deleteq;
}
}
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"位置非法";
else
{
s=newNode;s->data=x;
s->next=p->next;p->next=s;
}
}
int Student::Delete(int i)
{
intx;
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;
deleteq;
returnx;
}
}
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"位置非法";
elsereturn 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++;
}
return0;
}
void Student::Print()
{
Node*p;
p=first->next;
while(p!=NULL)
{
cout<<p->data<<",";
p=p->next;
}
}
void main()
{
intscore[5]={60,65,70,80,85};
StudentS(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;
}