实验三双链表

xiaoxiao2021-02-28  48

#include<iostream.h> template<class DataType> struct DulNode { DataType data; DulNode<DataType>*prior,*next; } ; template<class DataType> class ScoreList { public: ScoreList(); ScoreList(DataType a[],int n); ~ScoreList(); void Insert(int i,DataType x); int Search(DataType x); DataType Delete(int i); void Print(); private: DulNode<DataType>*first; }; template<class DataType> ScoreList<DataType>::ScoreList() { first=new DulNode<DataType>; first->next=NULL; } template<class DataType> ScoreList<DataType>::ScoreList(DataType a[],int n) { DulNode<DataType>*s; first=new DulNode<DataType>;     first->next=NULL; for(int i=0;i<n;i++) {s=new DulNode<DataType>; s->data=a[i];     s->next=first->next;     first->next=s;} } template<class DataType> ScoreList<DataType>::~ScoreList() { DulNode<DataType>*q; while(first!=NULL) { q=first; first=first->next; delete q; } } template<class DataType> void ScoreList<DataType>::Insert(int i,DataType x) { DulNode<DataType>*p=first,*s=NULL; int count=0; while(p!=NULL&&count<i-1) { p=p->next; count++; } if(p==NULL)throw"位置"; else{ s=new DulNode<DataType>;s->data=x; s->prior=p; s->next=p->next; p->next->prior=s; p->next=s; }  } template<class DataType> DataType ScoreList<DataType>::Delete(int i) { DulNode<DataType>*p=first,*q=NULL; DataType x; int count=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; (q->next)->prior=p->prior; delete q; return x; } } template<class DataType> int ScoreList<DataType>::Search(DataType x) { DulNode<DataType>*p=first->next; int count=1; while(p!=NULL) { if(p->data==x)return count; p=p->next; count++; } return 0; } template<class DataType> void ScoreList<DataType>::Print() {    DulNode<DataType>*p=first->next;    while(p!=NULL)    {     cout<<p->data<<" ";     p=p->next;    }    cout<<endl; } int main() { int a[5]={11,22,33,44,55}; ScoreList<int>S(a,5); cout<<"插入前数据为"<<endl; S.Print(); cout<<"在第3个位置插入成绩为60的元素"<<endl; try { S.Insert(3,60); } catch(char *s) { cout<<s<<endl; } cout<<"现数据为"<<endl; S.Print(); cout<<"删除第5个成绩"<<endl; S.Delete(5); cout<<"现数据为"<<endl; S.Print(); cout<<"查找成绩为55的位置"<<endl; cout<<S.Search(55)<<endl;

return 0;}

转载请注明原文地址: https://www.6miu.com/read-2625519.html

最新回复(0)