資料結構|建立學生成績的雙鏈表(實驗2.3)
阿新 • • 發佈:2019-01-23
一、實驗目的
鞏固線性表的資料結構的儲存方法和相關操作,學會針對具體應用,使用線性表的相關知識來解決具體問題。
二、實驗內容建立一個由n個學生成績的順序表,n的大小由自己確定,每一個學生的成績資訊由自己確定,實現資料的對錶進行插入、刪除、查詢等操作。分別輸出結果。
程式碼如下:
#include<iostream> using namespace std; template <class T> struct Node { T data; Node<T> *prior,*next; }; template <class T> class D { public: D(); D(T score[], int n); //有參建構函式 ~D(); //解構函式 int Length(); //返回單鏈表長度 void insert(int i, T x); //在位置i插入元素 T get(int i); //按位查詢 int locate(T x); //按值查詢 T Delete(int i); //刪除操作 void print(); //遍歷操作 private: Node<T> *first; //雙鏈表的頭指標 int length; }; template <class T> D<T>::D(T score[], int n) { length=0; first = new Node<T>; first->next = NULL; first->prior = NULL; for (int i = 0; i<n; i++) { Node<T> *s = new Node<T>; s->data = score[i]; s->next = first->next; first->next = s; } } template <class T> D<T>::~D() { while (first->next!=first->prior) { Node<T> *temp = first; first->prior->next = first->next; first->next -> prior = first->prior; //頭指標後移 first = first->next; delete temp; } delete first; } template<class T> int D<T>::Length() { Node<T> *p; int count; p=first->next; count=0; while(p!=NULL) { p=p->next; count++; } return length; } template <class T> void D<T>::insert(int i,T x) { Node<T>*p,*s; int count=0; p=first; while(p!=NULL&&count<i-1) { p=p->next; count++; } if(p==NULL) throw"位置"; else { s=new Node<T>; s->data=x; s->next=p->next; p->next=s; } } template <class T> T D<T>::get(int i) { Node<T> *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 T> int D<T>::locate(T x) { Node<T> *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 T> T D<T>::Delete(int i) { Node<T> *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 T> void D<T>::print() { Node<T> *p; p = first->next; while (p->next != NULL) { cout << p->data << " "; p = p->next; } cout << p->data << endl; } void main() { float score[8] = {88,89.5,89,79.5,96.5,76,100,88.5 }; D<float>student(score, 8); cout << " 學生的所有成績如下 " << endl; student.print(); cout << endl << "刪除在位置6的成績如下 :" << student.Delete(6) <<" , "<< "刪除後結果如下:" << endl; student.print(); cout << endl << "在位置7插入成績99,插入後結果如下:" << endl; student.insert(7,99); student.print(); cout << endl << "位置5的成績為:" << student.get(5) << endl; cout << endl << "成績100所在位置為:" << student.locate(100) << endl; }
執行結果如下: