#include<iostream>
using namespace std;
const int Maxsize=10;
template<class student>
struct Node {
student data;
Node<student> *next;
};
template<class student>
class inadd{
public:
inadd();//无参构造函数
inadd(student score[],int n);//有参构造函数
~inadd();//析构函数
void print();//遍历操作
student get(int i);//按位查找操作
int Locate(student x);//按值查找操作
void insert(int i,student x);//插入操作
student Delete(int i);//删除操作
bool changeList(int i,student x); //改变某一结点的值 i为节点的位置,x为替换的值
private:
Node<student> *first; //头指针
int length; //结点数量
Node<student> *address[Maxsize]; //结点指针数组
};
template<class student>
inadd<student>::inadd()
{
first=new Node<student>;
first->next=NULL;
}
template<class student>
inadd<student>::inadd(student score[],int n)
{
if (n>Maxsize) throw("溢出");
Node<student> *s;
first=new Node<student>;
first->next=NULL; //初始化一个空链表
for(int i=n-1;i>=0;i--)
{
s=new Node<student>;
s->data=score[i]; //为每个数组元素建立一个结点
s->next=first->next;
first->next=s; //将结点s插入头结点之后
}
}
template<class student>
inadd<student>::~inadd() //析构函数
{
Node<student> *q;
while(first!=NULL)
{
q=first;
first=first->next;
delete q;
}
}
template<class student>
void inadd<student>::insert(int i,student x)
{
Node<student>*p,*s;int count;
p=first;count=0;
while(p!=NULL&&count<i-1)
{
p=p->next;
count++;
}
if(p==NULL)throw"位置非法";
s=new Node<student>;
s->data=x;
s->next=p->next;
p->next=s;
length++;
}
template<class student>
student inadd<student>::Delete(int i)
{
Node<student> *q,*p;
student x;
int count;
p=first;count=0; //注意P指针要指向头结点
while(p!=NULL&&count<i-1) //此操作目的是找到i-1个结点
{
p=p->next;
count++;
}
if(p==NULL||p->next==NULL)throw"位置"; //结点p不存在或p后继结点不存在
else{
q=p->next;
x=q->data; //暂存被删结点
p->next=q->next;
delete q;
return x;
}
}
template<class student>
student inadd<student>::get(int i)
{
Node<student>*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;
}
template<class student>
int inadd<student>::Locate(student x)
{
Node<student>*p;
int count =1;
p=first->next;
while(p!=NULL)
{
if(p->data==x)return count;
p=p->next;
count++;
}
return 0;
}
template<class student>
void inadd<student>::print()
{
Node<student>*p;
p=first->next;
while(p!=NULL)
{cout<<p->data<<" ";
p=p->next;
}
}
int main()
{
float score[5]={88.5,52.5,99,73.5,98};
inadd<float>Student(score,5); //创建对象
cout<<"初始数据如下:"<<endl;
Student.print();
cout<<endl<<"在位置5插入成绩95,结果如下:"<<endl;
Student.insert(5,95);
Student.print();
cout<<endl<<"在学生2删除成绩为:"<<Student.Delete(2)<<endl<<"删除后结果如下:"<<endl;
Student.print();
cout<<endl<<"学生2的成绩为:"<<Student.get(3)<<endl;
cout<<endl<<"成绩99所在位置为:"<<Student.Locate(99)<<endl;
cout<<"最终数据如下:"<<endl;
Student.print();
cout<<endl;
return 0;
}
学生成绩——间接寻址
最新推荐文章于 2024-08-28 21:21:31 发布