雙鏈表-學生成績
阿新 • • 發佈:2018-11-05
#include<iostream.h> template<class T> struct Node { T data; Node<T>*next,*prior; }; template<class T> class Student { public: Student(); Student(T a[],int n); ~Student(); int Count(); int Locate(T x); void Insert(int i,T x); T Delete(int i); void Print(); private: Node<T>*first; }; template<class T> Student<T>::Count() { Node<T> *r=new Node<T>; r=first->next;int count=0; while(r!=NULL) { r=r->next; count++;} return count; } template<class T> Student<T>::Student() { first=new Node<T>; first->next=NULL; } template<class T> Student<T>::Student(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->prior=r; r->next=s;r=s; } r->next=NULL; } template<class T> Student<T>::~Student() { Node<T> *q=NULL; while(first!=NULL) { q=first; first=first->next; delete q; } } template<class T> void Student<T>::Insert(int i,T x) { Node<T>*p=first,*s=NULL; int count=0; while(p!=NULL&&count<i-1) { p=p->next; count++; } if(p==NULL)throw"位置"; else{ s=new Node<T>;s->data=x; s->prior=p; s->next=p->next;p->next->prior=s; p->next=s; } } template<class T> T Student<T>::Delete(int i) { Node <T>*p=first,*q=NULL; T x; int count=0; while(p!=NULL&&count<i-1) { p=p->next; count++; } if(p==NULL||p->next==NULL) throw"位置"; else { p->prior->next=p->next; p->next->prior=p->prior; delete q; return x; } } template<class T> int Student<T>::Locate(T x) { Node<T> *p=first->next; int count=1; while(p!=NULL) { if(p->data==x)return count; p=p->next; count++; } return 0; } template<class T> void Student<T>::Print() { Node<T>*p=first->next; while(p!=NULL) { cout<<p->data<<" "; p=p->next; } cout<<endl; } void main() { float r[5]={91,92,93,94,95}; Student<float>L(r,5); cout<<"一共有"<<L.Count()<<"學生成績"<<endl; L.Print(); cout<<"在第3位插入一個分數為100的學生"<<endl; L.Insert(4,100); cout<<"插入後一共有"<<L.Count()<<"學生成績"<<endl; L.Print(); cout<<"分數為93的學生位置為"; cout<<L.Locate(93)<<endl; cout<<"執行刪除第二個學生分數的操作,刪除前資料為:"<<endl; L.Print(); L.Delete(2); cout<<"刪除後資料為:"<<endl; L.Print(); }