一、实验目的
巩固线性表的数据结构的存储方法和相关操作,学会针对具体应用,使用线性表的相关知识来解决具体问题。
二、实验内容
建立一个由n个学生成绩的顺序表,n的大小由自己确定,每一个学生的成绩信息由自己确定,实现数据的对表进行插入、删除、查找等操作。分别输出结果
三、源代码
#include<iostream>
using namespace std;
template<typename T>
struct Node
{
T data;
Node<T> *next;
};
template<typename T>
class Linklist
{
private:
Node<T> *first;
public:
Linklist();
Linklist(T a[],int n);
~Linklist();
int length();
T Get(int i);
int locate(T x);
void Insert(int i,T x);
T Delete(int i);
void Print();
};
template<class T>
Linklist<T>::Linklist()
{
first=new node;
first->next=null;
}
template<class T>
Linklist<T>::Linklist(T a[],int n)
{
first=new Node<T>;
first->next=NULL;
for(int i=0;i<n;i++)
{
Node<T> *s;
s=new Node<T>;
s->data=a[i];
s->next=first->next;
first->next=s;
}
}
template<class T>
Linklist<T>::~Linklist()
{
while(first!=NULL)
{
Node<T> *q;
q=first;
first=first->next;
delete q;
}
}
template<class T>
int Linklist<T>::length()
{
Node<T> *p;
p=first->next;
int count=0;
while(p!=NULL)
{
p=p->next;
count++;
}
return count;
}
template<class T>
T Linklist<T>::Get(int i)
{
Node<T> *p;
p=first->next;
int count=1;
while(p!=NULL&&count<i)
{
p=p->next;
count++;
}
if(p==NULL) throw"位置";
else return p->data;
}
template<class T>
int Linklist<T>::locate(T x)
{
Node<T> *p;
p=first->next;
int count=1;
while(p!=NULL)
{
if(p->data==x)
return count;
p=p->next;
count++;
}
return 0;
}
template<class T>
void Linklist<T>::Insert(int i,T x)
{
Node<T> *p;
p=first;
int count=0;
while(p!=NULL&&count<i-1)
{
p=p->next;
count++;
}
if(p==NULL) throw"位置";
else
{
Node<T> *s;
s=new Node<T>;
s->data=x;
s->next=p->next;
p->next=s;
}
}
template<class T>
T Linklist<T>::Delete(int i)
{
Node<T> *p;
p=first;
int count=0;
while(p!=NULL&&count<i-1)
{
p=p->next;
count++;
}
if(p==NULL) throw"位置";
else
{
Node<T> *q;
q=p->next;
T x;
x=q->data;
p->next=q->next;
delete q;
return x;
}
}
template<class T>
void Linklist<T>::Print()
{
Node<T> *p;
p=first->next;
while(p!=NULL)
{
cout<<p->data;
cout<<" ";
p=p->next;
}
}
void main()
{
int b[10]={90,98,99,94,89,87,86,80,84,82};
Linklist<int>c(b,10);
cout<<"显示所有学生的成绩"<<endl;
c.Print();
cout<<endl;
cout<<"学生总数为:"<<c.length()<<endl;
cout<<"查找的第三位学生的成绩为:"<<endl;
cout<<c.Get(3)<<endl;
cout<<"查找成绩为99的学生:"<<endl;
cout<<c.locate(99)<<endl;
cout<<"在第二个学生前插入成绩为78的学生"<<endl;
try{c.Insert(2,78);}
catch(char *s)
{cout<<s<<endl;}
cout<<"插入后显示所有学生成绩"<<endl;
c.Print();
cout<<endl;
cout<<"删除第一个学生成绩后剩下学生的成绩为:"<<endl;
try{c.Delete(1);}
catch(char *s)
{cout<<s<<endl;}
c.Print();
}
四、运行结果
五、实验心得
通过这次的单链表实现的实验,我大概懂得单链表如何去实现各操作。当然,做这次的实验,卡到的点有很多,都是通过慢慢修改和在网上查找,最后运行成功了。