一、实验目的
巩固线性表的数据结构的存储方法和相关操作,学会针对具体应用,使用线性表的相关知识来解决具体问题。
建立一个由n个学生成绩的顺序表,n的大小由自己确定,每一个学生的成绩信息由自己确定,实现数据的对表进行插入、删除、查找等操作。分别输出结果。
源代码如下:
#include<iostream>
using namespace std;
const int Maxsize = 100;
template<class T>
struct Node
{
T data;
Node<T> *next;
};
template<class T>
class D{
public:
D();//无参构造函数
D(T score[],int n);//有参构造函数
virtual ~D();//析构函数
void print();//遍历操作
T get(int i);//按位查找操作
int locate(T x);//按值查找操作
void insert(int i,T x);//插入操作
T Delete(int i);//删除操作
bool changeList(int i, T x); //改变某一结点的值 i为节点的位置,x为替换的值
private:
Node<T> *first; //头指针
int length; //结点数量
Node<T> *address[Maxsize]; //结点指针数组
};
template<class T>
D<T>::D()
{
first=new Node<T>;
first->next=NULL;
}
template<class T>
D<T>::D(T score[],int n)
{
if (n > Maxsize) throw("溢出");
Node<T> *s;
first = new Node<T>;first->next=NULL; //初始化一个空链表
for(int i=n-1;i>=0;i--)
{
s=new Node<T>;s->data=score[i]; //为每个数组元素建立一个结点
s->next=first->next;first->next=s; //将结点s插入头结点之后
}
}
template<class T>
D<T>::~D() //析构函数
{
Node<T> *q;
while(first!=NULL)
{
q=first;
first=first->next;
delete q;
}
}
template<class T>
void D<T>::insert(int i,T x)
{
Node<T>*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<T>;s->data=x;
s->next=p->next;
p->next=s;
length++;
}
template<class T>
T D<T>::Delete(int i)
{
Node<T> *q,*p; T 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 T>
T D<T>::get(int i)
{
Node<T>*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 T>
int D<T>::locate(T x)
{
Node<T>*p;int count =1;
p=first->next;
while(p!=NULL)
{
if(p->data==x)return count;
p=p->next;
count++;
}
return 0;
}
template<class T>
void D<T>::print()
{
Node<T>*p;
p=first->next;
while(p!=NULL)
{cout<<p->data<<" ";;
p=p->next;
}
}
void main()
{
float score[8] = {88,89.5,89,79.5,96.5,76,100,88.5 };
D<float>student(score, 8);
cout << " 学生的所有成绩如下 " << endl;
student.print();
cout << endl << "删除在位置6的成绩如下 :" << student.Delete(6) <<" , "<< "删除后结果如下:" << endl;
student.print();
cout << endl << "在位置7插入成绩99,插入后结果如下:" << endl;
student.insert(7,99);
student.print();
cout << endl << "位置5的成绩为:" << student.get(5) << endl;
cout << endl << "成绩100所在位置为:" << student.locate(100) << endl;
}
运行结果如下: