线性表综合实验之双链表的实现

来源:互联网 发布:js跨域请求的几种方式 编辑:程序博客网 时间:2024/06/18 12:57
#include<iostream>using namespace std;template<class T>struct Node{T data;Node<T> *prior;Node<T> *next;};template<class T>class Doublelist{private:Node<T> *first;public:Doublelist();Doublelist(T a[],int n);~Doublelist(){}int Location_get(T x);void Insert(int i,T x);T Delete(int i);void Printlist();};template<class T>Doublelist<T>::Doublelist()  {      first=new Node<T>;      first->next=NULL;  }  template<class T>Doublelist<T>::Doublelist(T a[],int n) {      Node<T> *r,*s;      first=new Node<T>;      r=first;      for(int i=0;i<n;i++)      {          s=new Node<T>;          s->data=a[i];          s->next=NULL;          r->next=s;          s->prior=r;          r=s;      }      r->next=NULL;  }  template<class T>int Doublelist<T>::Location_get(T x)  {      Node<T> *p;p=first->next;      int count=1;      while(p!=NULL)      {          if(p->data==x) return count; else           p=p->next;          count++;    }      return 0;  }  template<class T>void Doublelist<T>::Insert(int i,T x)  {      Node<T> *p;Node<T> *s;p=first;    int count=0;      while(p!=NULL&&count<i-1)      {p=p->next;count++;}      if(p==NULL)throw"位置";      else{          s=new Node<T>;        s->prior=p;   s->next=p->next;    p->next->prior=s;        p->next=s;s->data=x;    }  }  template<class T>T Doublelist<T>::Delete(int i)  {      Node<T> *p=first;      int count=0;      while(p!=NULL&&count<i)      {          p=p->next;          count++;      }      if(p==NULL)          throw"位置";      else{          (p->prior)->next=p->next;          (p->next)->prior=p->prior;          delete p;      }      return 0;  }  template<class T>void Doublelist<T>::Printlist(){      Node<T> *p;    p=first->next;      while(p!=NULL)      {          cout<<p->data<<" ";          p=p->next;      }      cout<<endl;  }  int main(){int stu[10]={90,87,95,77,80,91,74,89,92,97};Doublelist<int> student(stu,10);cout<<"学生成绩如下:"<<endl;student.Printlist();cout<<"成绩为90的学生序号为:"<<student.Location_get(90)<<endl;cout<<"在序号为1的学生后面插进新成绩80:"<<endl;student.Insert(1,80);student.Printlist();cout<<"删除序号为2的学生的成绩:"<<endl;student.Delete(2);student.Printlist();return 0;}


一、实验目的


        巩固线性表的数据结构的存储方法和相关操作,学会针对具体应用,使用线性表的相关知识来解决具体问题。

二、实验时间


        准备时间为第3周到第4周,具体集中实验时间为第4周第2次课。2个学时。

三、实验内容


       1 、建立一个由n个学生成绩的顺序表,n的大小由自己确定,每一个学生的成绩信息由自己确定,实现数据的对表进行插入、删除、查找等操作。分别输出结果。

        2、用双链表实现。

四、实验结果截图



五、实验心得

        通过上一个单链表的实现的操作,对链表的实现有了一定的了解,所以在设计双链表的时候有部分程序都可以自己尝试着独立完成。但是又由于在双链表中同时运用了多个指针和数组来实现对数据的一些基本操作,而我本身就对指针数组这两方面的操作不是很理解和掌握,于是在做实验的过程中还是难免碰到了不少难题。最大的体会便是对插入学生成绩时各个指针之间的转换和含义有些混乱,导致在实验中没能快速实现相关操作;再者便是对于主函数的编写,其实主函数和单链表的基本相同,但是还没能对C++语言融会贯通的自己还是走了不少的弯路,在这块进行了较长时间的理解和修改。

       但总体还是在这个过程中认识到了更多的编程知识。

原创粉丝点击