1. 程式人生 > >實驗三:用順序表實現學生系統的基本操作

實驗三:用順序表實現學生系統的基本操作

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

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

原始碼:

# ifndef SeqList_H

# define SeqList_H

const int MaxSize=20;

template <class DataType>

class SeqList

{

public:

SeqList(){length=0;}

~SeqList(){}

SeqList(DataType a[],int n);

int Length(){return length;}

DataType Get(int i);

int Locate(DataType x);

void Insert(int i,DataType x);

DataType Delete(int i);

void PrintList();

private:

DataType data[MaxSize];

int length;

};

# endif

# include"SeqList.h"

# include<iostream>

using namespace std;

template<class DataType>

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

{

DataType i;

if(n>MaxSize) throw"上溢";

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

data[i]=a[i];

length=n;

}

template<class DataType>

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

{

if(i<1&&i>length) throw"查詢位置非法";

else return data[i-1];

}

template<class DataType>

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

{

int i;

for(i=0;i<length;i++)

if(data[i]==x) return i+1;

return 0;

 

}

template<class DataType>

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

{

int j;

if(length>=MaxSize) throw"上溢";

if(i<1||i>length+1) throw"位置";

for(j=length;j>=i;j--)

data[j]=data[j-1];

data[i-1]=x;

length++;

}

template<class DataType>

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

{

int x,j;

if(length==0) throw"下溢";

if(i<1||i>length) throw"位置";

x=data[i-1];

for(j=i;j<length;j++)

data[j-1]=data[j];

length--;

return x;

}

template<class DataType>

void SeqList<DataType>::PrintList()

{

int i;

for(i=0;i<length;i++)

cout<<data[i]<<endl;

}

# include"SeqList.cpp"

# include<iostream>

using namespace std;

int main()

{

int r[10],i;

for(i=0;i<10;i++)

cin>>r[i];

SeqList<int>S(r,10);

S.PrintList();

cout<<"The Second grade is "<<S.Get(2)<<endl;

cout<<"The Location of 90 is "<<S.Locate(90)<<endl;

S.Insert(3,65);

S.Delete(2);

S.PrintList();

return 0;

}

程式結果: