1. 程式人生 > >實驗三:用單鏈表實現基本的學生管理系統

實驗三:用單鏈表實現基本的學生管理系統

實驗目的:鞏固線性表的資料的儲存方法和相關操作,學會針對具體應用,使用線性表的相關知識來解決具體問題。

實驗內容:建立一個由n個學生成績的線性表,n的大小由自己確定,每個學生的成績資訊由自己確定,實現資料的對錶進行插入、刪除、查詢等操作。

源程式:

# ifndef LinkList_H

# define LinkList_H

template<class DataType>

struct Node

{

DataType data;

Node<DataType>*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:

Node<DataType>*first;

};

# endif

# include"LinkList.h"

# include<iostream>

using namespace std;

template<class DataType>

LinkList<DataType>::LinkList()

{

first=new Node<DataType>;

first->NULL;

}

template<class DataType>

LinkList<DataType>::LinkList(DataType a[],int n)

{

Node<DataType>*r,*s;

first=new Node<DataType>;

r=first;

for(int i=0;i<n;i++)

{

s=new Node<DataType>;

s->data=a[i];

r->next=s;

r=s;

}

r->next=NULL;

}

template<class DataType>

LinkList<DataType>::~LinkList()

{

Node<DataType>*q=NULL;

while(first!=NULL)

{

q=first;

first=first->next;

delete q;

}

}

template<class DataType>

int LinkList<DataType>::Length()

{

Node<DataType> *p;

p=first;

int count=0;

while(p!=NULL)

{

p=p->next;

count++;

}

return count;

}

template<class DataType>

DataType LinkList<DataType>::Get(int i)

{

Node<DataType>*p;

p=first->next;

int count=1;

while(p!=NULL&&count<1)

{

p=p->next;

count++;

}

if(p==NULL) throw"位置";

else return p->data;

}

template<class DataType>

int LinkList<DataType>::Locate(DataType x)

{

Node<DataType>*p;

p=first->next;

int count=1;

while(p!=NULL)

{

if(p->data==x) return count;

p=p->next;

count++;

}

return 0;

}

template<class DataType>

void LinkList<DataType>::Insert(int i,DataType x)

{

Node<DataType>*p=first,*s=NULL;

int count=0;

while(p!=NULL&&count<i-1)

{

p=p->next;

count++;

}

if(p==NULL) throw"位置";

else

{

s=new Node<DataType>;

s->data=x;

s->next=p->next;

p->next=s;

}

 

}

template<class DataType>

DataType LinkList<DataType>::Delete(int i)

{

Node<DataType>*p=first,*q=NULL;

DataType x;

int count=0;

while(p!=NULL&&count<i-1)

{

p=p->next;

count++;

}

if(p==NULL||p->next==NULL)

throw"位置";

else

{

q=p->next;

x=q->data;

p->next=q->next;

delete q;

return x;

}

}

template<class DataType>

void LinkList<DataType>::PrintList()

{

Node<DataType> *p;

p=first->next;

while(p!=NULL)

{

cout<<p->data<<endl;

p=p->next;

cout<<endl;

}

# include<iostream>

using namespace std;

# include"LinkList.cpp"

int main()

{

int r[5];

for(int i=0;i<5;i++)

cin>>r[i];

LinkList<int>L(r,5);

L.PrintList();

cout<<L.Length()<<endl;

cout<<L.Get(2)<<endl;

cout<<L.Locate(80)<<endl;

L.Insert(3,65);

L.Delete(2);

L.PrintList();

cout<<endl;

return 0;

}

程式結果: