一.实验目的
巩固线性表的数据结构的存储方法和相关操作,学会针对具体应用,使用线性表的相关知识来解决具体问题。
二.实验内容
建立一个由n个学生成绩的顺序表,n的大小由自己确定,每一个学生的成绩信息由自己确定,实现数据的对表进行插入、删除、查找等操作。分别输出结果。(双链表)
源代码:
#include<iostream>
#include<fstream>
using namespace std;
template<class D>
struct Node
{
D data;
Node<D>*prior;
Node<D>*next;
};
template<class D>
class Doublylinked
{
private:
Node<D>*head;
Node<D>*rear;
int length;
public:
Doublylinked(D a[],int n);//构造函数
void printlist();//显示双链表
D getlist(int i);//得到第i位数据
int locate(D x);//查找数据为第X位
void insert(int a,D x);//插入数据
D deletelist(int a);//删除数据
};
template<class D>
Doublylinked<D>::Doublylinked(D a[],int n)
{
head = new Node<D>;
head->prior=NULL;
rear = head;
for (int i=0;i<n;i++)
{
Node<D>*s = new Node<D>;
s->data=a[i];
s->next = NULL;
s->prior = rear;
rear->next = s;
rear = s;
}
}
template<class D>
void Doublylinked<D>::printlist()
{
Node<D>*p = head->next;
while(p!=NULL)
{
cout<<p->data<<" ";
p = p->next;
}
cout<<endl;
}
template<class D>
D Doublylinked<D>::getlist(int i)
{
Node<D>*p = head->next;
int count = 1;
while(p!=NULL&&count<i)
{
p=p->next;
count++;
}
if(p==NULL)throw"位置错误";
else return p->data;
}
template<class D>
int Doublylinked<D>::locate(D x)
{
Node<D>*p = head->next;
int count=1;
while(p!=NULL)
{
if(p->data==x)
return count;
p=p->next;
count++;
}
return 0;
}
template<class D>
void Doublylinked<D>::insert(int a,D x)
{
Node<D>*p = new Node<D>;
Node<D>*q = head;
p->data = x;
for (int i=0;i<a;i++)
{
q = q->next;
}
p->prior = q->prior;
q->prior->next = p;
p->next = q;
q->prior = p;
length++;
}
template<class D>
D Doublylinked<D>::deletelist(int a)
{
Node<D>*p = head->next;
for (int i=0;i<a-1;i++)
{
p = p->next;
}
p->prior->next = p->next;
p->next->prior = p->prior;
Node<D>*q = p;
delete p;
length--;
return q->data;
}
void main()
{
int a[5]={100,94,91,89,76,};
Doublylinked<int> double1(a,5);
cout<<"5人成绩:"<<endl;
double1.printlist();
cout<<endl;
cout<<"排名第3的成绩为:"<<endl;
cout<<double1.getlist(3)<<endl;
cout<<"76分的同学排名为:"<<endl;
cout<<double1.locate(76)<<endl;
cout<<"第五位插入成绩66:"<<endl;
double1.insert(5,66);
cout<<"当前表为:"<<endl;
double1.printlist();
cout<<endl;
cout<<"删除第三位成绩"<<endl;
double1.deletelist(3);
cout<<"当前表为:"<<endl;
double1.printlist();
cout<<endl;
}
运行结果:
心得体会
我觉得双链表最难的是创表和插入删除数据,单看书不能解决问题,需要从网上观察程序指针使用的方法,很灵活,但同时也很容易把自己搞乱。除了这几个难点外,双链表和单链表有相似之处,也要唯一确定头指针,使操作变得简单。双链表的好处是可以顺序和倒序浏览数据,使用更加灵活。