1. 程式人生 > >實驗三 單鏈表實現學生成績管理系統

實驗三 單鏈表實現學生成績管理系統


 
  #include<iostream> using namespace std; //template<class DataType> typedef int DataType; struct Node { DataType data; struct Node *next; }; //template<class DataType> class Linklist { 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(); private: struct Node *first; }; //template<class DataType> void Linklist::Printlist() { Node *p; int i=0; p=first->next; while(p!=NULL) { i=i+1; cout<<"第"<<i<<"個學生成績:"<<p->data<<endl; p=p->next; } } //template<class DataType> int Linklist::Length() { struct Node *p; p=first->next; int count=0; while(p!=NULL) { p=p->next; count++; } return count; } //template<class DataType> DataType Linklist::Get(int i) { struct Node *p; p=first->next; int count=1; while(p!=NULL&&count<i) { p=p->next; count++; } if(p==NULL) cout<<"位置"<<endl; else cout<<p->data<<endl; return 0; } //template<class DataType> int Linklist::Locate(DataType x) { struct Node *p; p=first->next; int count=1; while(p!=NULL) { if(p->data==x)
 
 
   { cout<<count<<endl; return 1; } p=p->next; count++; } cout<<"無此成績"<<endl; return 0; } //template<class DataType> void Linklist::Insert(int i,DataType x) { struct Node *p,*s; p=first; int count=0; while(p!=NULL&&count<i-1) { p=p->next; count++; } if(p==NULL) cout<<"位置"<<endl; else { s=new Node; s->data=x; s->next=p->next; p->next=s; } } //template<class DataType> Linklist::Linklist() { first=new Node; first->next=NULL; } //template<class DataType> Linklist::Linklist(DataType a[],int n) { struct Node *s; first=new Node; first->next=NULL; for(int i=0;i<n;i++) { s=new Node; s->data=a[i]; s->next=first->next; first->next=s; } } //template<class DataType> DataType Linklist::Delete(int i) { struct Node *p,*q; p=first; int count=0,x; while(p!=NULL&&count<i-1) { p=p->next; count++; } if(p==NULL||p->next==NULL) cout<<"位置"<<endl; else { q=p->next; x=q->data; p->next=q->next; delete q; return x; } return 0; } //template<class DataType> Linklist::~Linklist() { struct Node *q; while(first!=NULL) { q=first; first=first->next; delete q; } } //template<class DataType> int main() { cout<<"單鏈表實現學生成績"<<endl; int score[3]={77,88,99}; Linklist L(score,3); cout<<"學生的資料結構成績為:"<<endl; L.Printlist(); cout<<endl<<endl<<"在位置2插入成績66:"<<endl; L.Insert(2,66); L.Printlist(); cout<<endl<<endl<<"在位置1刪除:"<<endl; L.Delete(1); L.Printlist(); cout<<endl<<endl<<"位置3的成績為:"<<endl; L.Get(3); cout<<endl<<endl<<"成績為88所在的位置為:"<<endl; L.Locate(88); cout<<endl; return 0; }