实验二 线性表综合实验--双链表
一.实验目的
巩固线性表的数据结构的存储方法和相关操作,学会针对具体应用,使用线性表的相
关知识来解决具体问题。
二.实验内容
1.建立一个由n个学生成绩的顺序表,n的大小由自己确定,每一个学生的成绩信息由自
己确定,实现数据的对表进行插入、删除、查找等操作。分别输出结果。
三.源代码
#include "stdafx.h"
#include<iostream>
using namespace std;
template <class DT>
class Node{
public:
DT data;
Node<DT> *prior;
Node<DT> *next;
};
template <class DT>
class DoubleLinkList {
public:
DoubleLinkList();
DoubleLinkList(DT a[], int n); //有参构造函数
~DoubleLinkList(); //析构函数
void insert(int i, DT x); //插入操作,在位置i插入元素
DT get(int i); //按位查找
int locate(DT x); //按值查找
DT Delete(int i); //删除操作
void printlist(); //遍历操作
private:
Node<DT> *first; //双链表的头指针
int length; //链的长度计数
};
template <class DT>
DoubleLinkList<DT>::DoubleLinkList(DT a[],int n)
{
first = new Node<DT>;
first->next = NULL;
first->prior = NULL;
for (int i = n-1; i>=0; i--)
{
Node<DT> *s = new Node<DT>;
s->data = a[i];
s->next = first->next;
first->next = s;
}
}
template <class DT>
DoubleLinkList<DT>::~DoubleLinkList()
{
while (first->next != first->prior)
{
Node<DT> *temp = first; //脱链
first->prior->next = first->next;
first->next->prior = first->prior; //头指针后移
first = first->next; //释放内存
delete temp;
}
delete first;
}
template <class DT>
void DoubleLinkList<DT>::insert(int i,DT x)
{
Node<DT>*p, *s; int count;
p = first;
count = 0;
while (p != NULL&&count<i - 1)
{
p = p->next;
count++;
}
if (p == NULL) throw"位置";
else
{
s = new Node<DT>;
s->data = x;
s->next = p->next;
p->next = s;
}
}
template <class DT>
DT DoubleLinkList<DT>::get(int i)
{
Node<DT> *p; int count; count = 1;
p = first->next;
while (p != NULL&&count<i)
{
p = p->next; count++;
}
if (p == NULL)throw"位置非法";
else return p->data;
}
template <class DT>
int DoubleLinkList<DT>::locate(DT x)
{
Node<DT> *p; int count;
p = first->next; count = 1;
while (p != NULL)
{
if (p->data == x) return count;
p = p->next;
count++;
}
return 0;
}
template <class DT>
DT DoubleLinkList<DT>::Delete(int i)
{
Node<DT> *p, *q;
p = first->next;
int count, x;
count = 1;
while (p != NULL&&count<i - 1)
{
p = p->next; count++;
}
if (p == NULL || p->next == NULL) throw"位置非法";
else
{
q = p->next;
x = q->data;
if (p->next != NULL)
{
if (q->next != NULL)
q->next->prior = p;
else
{
p->next = NULL;
p->next = q->next;
delete q;
q = NULL;
return x;
}
}
p->next = q->next;
delete q;
q = NULL;
return x;
}
}
template <class DT>
void DoubleLinkList<DT>::printlist()
{
Node<DT> *p;
p = first->next;
while (p->next != NULL)
{
cout << p->data << " ";
p = p->next;
}
cout << p->data << endl;
}
void main()
{
int a[10] = { 91,53,75,67,49,11,100,25,84,66 };
DoubleLinkList<int> D(a, 10);
cout<<"遍历所有分数"<<endl;
D.printlist();//遍历之前分数
cout<<"第五个元素的分数"<<endl;
cout << D.get(5) << endl;
cout<<"在第二个位置插入分数78"<<endl;
D.insert(2, 78);
cout<<"遍历插入数据后的所有分数"<<endl;
D.printlist();
cout<<"值为11的位置为:"<<endl;
cout << D.locate(11) << endl;
cout<<"遍历之前的分数"<<endl;
D.printlist();
cout<<"删除位置为8的分数"<<endl;
cout<<D.Delete(8)<<endl;
cout<<"删除分数后遍历所有分数"<<endl;
D.printlist();
}
四、实验总结
课堂掌握了知识,并不是真正就了解它,只有在实践中,才能知道自己的不足之处在哪,并经过多遍尝试去解决它。