学生成绩——单链表

xiaoxiao2021-02-28  53

#include<iostream> using namespace std; template<class Datatype> struct Node //设置结点 { Datatype data; Node<Datatype> *next; }; template <class Datatype> class Linklist { Node<Datatype> *first; public: Linklist(); Linklist(Datatype a[],int n); ~Linklist(); int length();//求链表长度 Datatype get(int i);//按位查找 int locate(Datatype x);//按值查找 void insert(int i,Datatype x);//插入 Datatype Delete(int i);//删除 void printlist();//遍历 }; //成员函数的定义 template <class Datatype> Linklist<Datatype>::Linklist() { first=new Node<Datatype>; first->next=NULL; } template<class Datatype> void Linklist<Datatype>::printlist() { Node<Datatype> *p=NULL; p=first->next; cout<<"输出成绩:"; while(p!=NULL) { cout<<p->data<<" "; p=p->next; } } template<class Datatype> Linklist<Datatype>::Linklist(Datatype a[],int n) { Node<Datatype> *s; first=new Node<Datatype>; first->next=NULL; for(int i=0;i<n;i++) { s=new Node<Datatype>; s->data=a[i]; s->next=first->next; first->next=s; } } template<class Datatype> Linklist<Datatype>::~Linklist() { Node<Datatype> *q=NULL; while(first!=NULL) { q=first; first=first->next; delete q; } cout<<"\n数据清空,欢迎再次使用!"<<endl; } template<class Datatype> int Linklist<Datatype>::length() { Node<Datatype> *p=NULL; p=first->next; int count=0; while(p!=NULL) { p=p->next; count++; } return count; } template<class Datatype> Datatype Linklist<Datatype>::get(int i) { Node<Datatype> *p=NULL; p=first->next; int count=1; while(p!=NULL&& count<i) { p=p->next; count++; } if(p==NULL) throw"溢出"; else {return p->data;} } template<class Datatype> int Linklist<Datatype>::locate(Datatype x) { Node<Datatype> *p=NULL; 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 Linklist<Datatype>::insert(int i,Datatype x) { Node<Datatype> *p,*s; p=first; int count=0; while(p!=NULL && count<i-1) { p=p->next; count++; } if(p==NULL) throw"溢出"; else {s=new Node<Datatype>; s->data=x; s->next=p->next; p->next=s;} } template<class Datatype> Datatype Linklist<Datatype>::Delete(int i) { Node<Datatype> *p; p=first; int count=0; while(p!=NULL&&count<i-1){ p=p->next; count++; } if(p==NULL||p->next==NULL) throw"位置"; else {Node<Datatype> *q=NULL; q=p->next; Datatype x=q->data; p->next=q->next; delete q; return x; } } int main(){ int stu_score[6]={53,78,96,56,88,68}; Linklist<int>list1(stu_score,6); cout<<"初始成绩如下!"<<endl; list1.printlist();//遍历 cout<<endl; cout<<"1、按位查找\n第3位学生的分数为:"<<list1.get(4)<<endl;//按位查找 cout<<"2、按值查找\n96分所在的学生位置在第"<<list1.locate(96)<<"位"<<endl;//按值查找 cout<<"此时的数据长度为:"<<list1.length()<<endl;//长度 cout<<"在第4个学生位置插入88"<<endl; list1.insert(4,88);//插入 list1.printlist(); cout<<endl; cout<<"此时的数据长度为:"; cout<<list1.length()<<endl; cout<<"删除第一个分数!"<<list1.Delete(1)<<endl;//删除 list1.printlist(); cout<<endl; }
转载请注明原文地址: https://www.6miu.com/read-2631568.html

最新回复(0)