《数据结构》实验二:线性表实验
《数据结构》实验二:线性表实验 一、实验目的 巩固线性表的数据结构,学会线性表的应用。1.回顾线性表的逻辑结构,线性表的物理存储结构和常见操作。2.学习运用线性表的知识来解决实际问题。3.进一步巩固程序调试方法。4.进一步巩固模板程序设计。 二、实验内容1.建立一个N个学生成绩的顺序表,对表进行插入、删除、查找等操作。分别输出结果。要求如下:1)用顺序表来实现。#include<iostream> } 2)用单链表来实现。 #include<iostream> usingnamespacestd;
template<classScore> structNode { Scoredata; Node<Score>*next; }; template<classScore> classLinklist { public: Linklist(); Linklist(Scorea[],intn); ~Linklist(); intLocate(Scorex); voidInsert(inti,Scorex); ScoreDelete(inti); voidPrintlist(); private: Node<Score>*first; }; template<classScore> Linklist<Score>::Linklist() { first=newNode<Score>; first->next=NULL; } template<classScore> Linklist<Score>::Linklist(Scorea[],intn) { Node<Score>*r,*s; first=newNode<Score>; r=first; for(inti=0;i<n;i++) { s=newNode<Score>; s->data=a[i]; r->next=s;r=s; } r->next=NULL; } template<classScore> Linklist<Score>::~Linklist() { Node<Score>*q=NULL; while(first!=NULL) { q=first; first=first->next; deleteq; } } template<classScore> voidLinklist<Score>::Insert(inti,Scorex) { Node<Score>*p=first,*s=NULL; intcount=0; while(p!=NULL&&count<i-1) { p=p->next; count++; } if(p==NULL)throw"位置"; else{ s=newNode<Score>;s->data=x; s->next=p->next;p->next=s; } } template<classScore> ScoreLinklist<Score>::Delete(inti) { Node<Score>*p=first,*q=NULL; Scorex; intcount=0; while(p!=NULL&&count<i-1) { p=p->next; count++; } if(p==NULL||p->next==NULL) throw"位置"; else{ q=p->next; x=q->data; p->next=q->next; deleteq; returnx; } } template<classScore> intLinklist<Score>::Locate(Scorex) { Node<Score>*p=first->next; intcount=1; while(p!=NULL) { if(p->data==x)returncount; p=p->next; count++; } return0; } template<classScore> voidLinklist<Score>::Printlist() { Node<Score>*p=first->next; while(p!=NULL) { cout<<p->data<<""; p=p->next; } cout<<endl; } voidmain() { intr[10]={72,49,82,61,83,98,70,73,84}; Linklist<int>L(r,10); cout<<"执行插入操作前的数据为:"<<endl; L.Printlist(); try { L.Insert(3,89); } catch(char*s) { cout<<s<<endl; } cout<<"执行插入操作后的数据为:"<<endl; L.Printlist(); cout<<"值为100的元素的位置为:"; cout<<L.Locate(100)<<endl; cout<<"执行删除操作前的数据为:"<<endl; L.Printlist(); try { L.Delete(1); } catch(char*s) { cout<<s<<endl; } cout<<"执行删除操作后的数据为:"<<endl; L.Printlist(); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |