學生成績——雙鏈表
阿新 • • 發佈:2018-12-02
#include<iostream> using namespace std; template <class student> class Node { public: student data; Node<student> *prior; Node<student> *next; }; template <class student> class DLL { public: DLL(); //無參的建構函式 DLL(student score[], int n); //帶參的建構函式 ~DLL(); //解構函式 int Length(); //返回單鏈表長度 void insert(int i, student x); //插入操作,在位置i插入元素 student get(int i); //按位查詢 int locate(student x); //按值查詢 student Delete(int i); //刪除操作 void print(); //遍歷操作 private: Node<student> *first; //雙鏈表的頭指標 int length; //鏈的長度計數 }; template <class student> DLL<student>::DLL(student score[], int n) { length=0; first=new Node<student>; first->next=NULL; first->prior=NULL; for (int i=0;i<n;i++) { Node<student> *s=new Node<student>; s->data=score[i]; s->next=first->next; first->next = s; } } template <class student> DLL<student>::~DLL() { while (first->next!=first->prior) { //臨時指標,儲存即將釋放的節點的指標 Node<student> *temp=first; //脫鏈 first->prior->next=first->next; first->next ->prior=first->prior; //頭指標後移 first=first->next; //釋放記憶體 delete temp; } delete first; } template<class student> int DLL<student>::Length() { Node<student> *p; int count; p=first->next; count=0; while(p!=NULL) { p=p->next; count++; } return length; } template <class student> void DLL<student>::insert(int i,student x) { Node<student>*p,*s; int count; p=first; count=0; while(p!=NULL&&count<i-1) { p=p->next; count++; } if(p==NULL) throw"位置"; else { s=new Node<student>; s->data=x; s->next=p->next; p->next=s; } } template <class student> student DLL<student>::get(int i) { Node<student> *p;int count; count=1; p=first->next; while (p!=NULL&&count<i) { p = p->next; count++; } if (p == NULL)throw"位置非法"; else return p->data; } template <class student> int DLL<student>::locate(student x) { Node<student> *p; int count; p=first->next; count=1; while(p!=NULL) { if(p->data==x) return count; p=p->next; count++; } return 0; } template <class student> student DLL<student>::Delete(int i) { Node<student> *p,*q; p=first->next; int count, x; count=1; while (p!=NULL&&count<i-1) { p=p->next; count++; } if (p==NULL||p->next==NULL) throw"位置非法"; else { q=p->next; x=q->data; if (p->next!=NULL) { if(q->next!=NULL) q->next->prior=p; else { p->next=NULL; p->next=q->next; delete q; q=NULL; return x; } } p->next=q->next; delete q; q=NULL; return x; } } template <class student> void DLL<student>::print() { Node<student> *p; p=first->next; while(p->next!=NULL) { cout<<p->data<<" "; p=p->next; } cout<<p->data<<endl; } int main() { float score[8] = {72,88,57,83.5,32.5,68,96,86.5}; DLL<float>Student(score, 8); cout<<"初始成績如下:"<<endl; Student.print(); cout<<endl<<"在學生3插入成績86,插入後結果如下:"<<endl; Student.insert(3,86); Student.print(); cout<<endl<<"在學生5刪除成績為:"<<Student.Delete(5)<<" , "<<"刪除後結果如下:"<<endl; Student.print(); cout<<endl<<"位置6的成績為:"<<Student.get(6)<<endl; cout<<endl<<"成績72所在位置為:"<<Student.locate(72)<<endl<<endl; cout<<"最終資料如下:"<<endl; Student.print(); cout<<endl; return 0; }