#include <iostream> using namespace std; const int N=5; struct Std{ int date; Std *next; }*p,*r; class Student{ private: Std *first; int length; public: Student(); Student(int a[],int n); ~Student(){} void Insert(int i,int x); int Delete(int i); int Get(int i); int Locate(int x); void Show(); }; Student::Student(){ first =new Std; first->next=NULL; } Student::Student(int a[],int n){ first=new Std; first->next=NULL; r=first; for (int i=0;i<n;i++){ p=new Std; p->date=a[i]; r->next=p; r=p; } r->next=NULL; lenght=n; } void Student::Insert(int i,int x){ r=first; int j=0; while (r!=NULL&&j<i-1){ r=r->next; j++; } if (r==NULL) throw "位置非法"; else { p=new Std; p->next=r->next; p->date=x; r->next=p; length++; } } int Student::Delete(int i){ r=first; int j=0; while (r!=NULL&&j<i-1){ r=r->next; j++; } if (r==NULL) throw "位置非法"; else { p=r->next; r->next=p->next; delete p; lenght--; } return p->date; } int Student::Get(int i) { r = first; int j = 0; while (r != NULL && j<i - 1) { r = r->next; j++; } if (r == NULL) throw "位置非法"; else p = r; return p->date; } int Student::Locate(int x) { r = first; int j=0; while (r != NULL) { r = r->next; j++; if (r->date == x) break; } if (r == NULL) throw "位置非法"; return j; } void Student::Show() { r = first; while (r->next!= NULL) { r = r->next; cout << r->date << ' '; } cout<<endl; } int main() { int a[3] = { 90,80,75 }; Student S(a, 3); cout << "原表:" << endl; S.Show(); cout << "在第3位插入98:" << endl; S.Insert(3, 98); cout << "插入后:" << endl; S.Show(); cout << "删除第2位:" << endl; S.Delete(2); cout << "删除后:" << endl; S.Show(); cout << "查75分的位置:" << S.Locate(75) << ',' << "查第2位的成绩:" << S.Get(2) << endl; return 0; }
实验三单链表
猜你喜欢
转载自blog.csdn.net/weixin_41937706/article/details/80266136
今日推荐
周排行