學生成績——靜態連結串列
阿新 • • 發佈:2018-12-02
#include<iostream> #include<string> using namespace std; const int Maxsize=10; template<class student> class Node { public: student data; int next; //儲存陣列下標 }; template <class student> class SLL { public: SLL();//無參建構函式 SLL(student score[],int n);//帶參建構函式 ~SLL();//空的解構函式 void print();//遍歷操作 student get(int i);//按位查詢操作 int Locate(student x);//按值查詢操作 void insert(int i,student x);//插入操作 void Delete(int i);//刪除操作 private: Node<student> node[Maxsize];//資料成員結點 int first;//頭指標 int avail;//指向空閒鏈的頭指標 int length;//當前靜態連結串列的長度 }; template<class student> SLL<student>::SLL(student score[],int n) { length=0; for(int i=0;i<Maxsize;i++) { node[i].next=i+1; } node[Maxsize-1].next=-1; avail=2; first=1; node[first].next=-1; for(int j=n-1;j>=0;j--) { if (avail==-1) { break; } int s=avail; avail=node[avail].next;//空閒鏈的頭指標後移 node[s].data=score[j];//將score[j]填入下標為S的節點 node[s].next=node[first].next;//將score[j]插到first後面 node[first].next=s; //將s接入first後面 length++; } } template<class student> SLL<student>::~SLL() {} template<class student> void SLL<student>::print() { int s=node[first].next; for (int i=1;i<=length;i++) { cout<<node[s].data<<" "; s=node[s].next; } } template<class student> student SLL<student>::get(int i) { if(i<=0||i>length) throw"位置非法"; int p=first; for(int j=0;j<i;j++) { p=node[p].next; } return node[p].data; } template<class student> int SLL<student>::Locate(student x) { int count=0; int p=first; while(node[p].next!=-1) { p=node[p].next; if(node[p].data==x) return count+1; count++; } return -1; } template<class student> void SLL<student>::insert(int i, student x) { if(i<0||i>length) throw"位置非法"; int p=first; for(int j=1;j<i;j++) { p=node[p].next; } int s=node[avail].next; node[avail].data=x; node[avail].next=node[p].next; node[p].next=avail; avail=s; length++; } template<class student> void SLL<student>::Delete(int i) { if(i<0||i>length+1) throw"位置非法"; int p = first; for(int j = 1;j<=i; j++) { p=node[p].next; } int q = node[p].next; student e = node[p].data; node[p].next = node[q].next; node[q].next = avail; avail = q; length--; } int main() { float score[5]={79.5,68,88.5,84.5,99}; SLL<float> Student(score,5); cout<<"初始資料如下:"<<endl; Student.print(); cout<<endl<<"在學生5插入成績90.5:"<<endl; Student.insert(5,90.5); Student.print(); cout<<endl<<"在學生3刪除成績:"<<endl; Student.Delete(2); Student.print(); cout<<endl<<"學生5的成績為:"<<Student.get(5)<<endl; cout<<endl<<"成績99所在學生為:"<<Student.Locate(99)<<endl<<endl; cout<<"最終資料如下:"<<endl; Student.print(); cout<<endl; return 0; }