静态链表-学生成绩


#include<iostream.h>    
const int Maxsize=20;    
template<class T>    
struct Node    
{    
    T data;    
    int next;    
};    
template<class T>    
class Student    
{    
    private:    
        Node<T> List[Maxsize];    
        int first,avail;    
    public:    
        Student();    
        Student(T s[],int n);    
        ~Student(){count--;}    
        int Length(){return count;}    
        void Insert(T x);    
        T Get(int i);    
        int Locate(T x);    
        void Delete(int i);    
        void Print();    
        static int count;    
};    
template<class T>    
int Student<T>::count=0;    
template<class T>    
Student<T>::Student()    
{    
    first=0;avail=1;    
    List[first].next=-1;    
    List[first].data=NULL;    
}    
template<class T>    
Student<T>::Student(T s[],int n)    
{    
    first=0;avail=1;    
    List[first].next=1;    
    List[avail].data=NULL;    
    for(int i=0;i<n;i++)    
    {    
        List[avail].data=s[i];    
        List[avail].next=avail+1;    
        avail++;    
        count++;    
    }    
    List[avail].next=-1;    
}    
template<class T>    
T Student<T>::Get(int i)    
{    
    T x;    
    if(i<1||i>count)throw"位置";    
    for(int n=0;n<count;n++)    
    {    
        if(List[n].next==i)x=List[i].data;    
    }    
    return x;    
}    
template<class T>    
int Student<T>::Locate(T x)    
{    
    for(int i=1;i<=count;i++)    
        if(List[i].data==x)return List[i-1].next;    
        return 0;    
}    
template<class T>    
void Student<T>::Insert(T x)    
{    
    avail=count;    
    if(count==Maxsize)throw"上溢";    
    List[avail].next=avail+1;    
    List[avail+1].data=x;    
    List[avail+1].next=-1;    
    count++;    
}    

template<class T>    
void Student<T>::Delete(int i)    
{    
    if(i<1||i>count)return;    
    else{    
        List[i-1].next=List[i].next;    
        List[i].next=-1;    
        List[i].data=NULL;    
        count--;    
    }    
}    
template<class T>    
void Student<T>::Print()    
{    
    int s=List[first].next;    
    for(int i=1;i<=count;i++)    
    {    
        cout<<List[s].data<<" ";    
        s=List[s].next;    
}    
}    
void main()    
{    
    float r[5]={91,92,93,94,95};    
    Student<float> L(r,5);    
    cout<<"一共有"<<L.Length()<<"学生成绩"<<endl;    
    L.Print();    
    cout<<endl;    
    cout<<"在第5位插入一个分数为100的学生";    
    L.Insert(100);    
    cout<<endl;    
    cout<<"插入后一共有"<<L.Length()<<"学生成绩"<<endl;    
    L.Print();    
    cout<<endl;    
    cout<<"分数为93的学生位置为";    
    cout<<L.Locate(93)<<endl;    
    cout<<"执行删除第二个学生分数的操作,删除前数据为:"<<endl;    
    L.Print();    
    L.Delete(2);cout<<endl;    
    cout<<"删除后数据为:"<<endl;    
    L.Print();cout<<endl;    
}    

猜你喜欢

转载自blog.csdn.net/ab111996/article/details/80706435