数据结构实验三之单链表.

2..建立一个由n个学生成绩的顺序表,实现对数据的插入,删除,查找等操作。

源代码:

#ifndef Student_H

#define Student_H

template<class DataType>

struct Node

{

DataType data;

Node<DataType>*next;

};

template<class DataType>

class Student

{

public:

Student();

Student(DataType a[],int n);

~Student();

void Insert(int i,DataType x);

int Locate(DataType x);

DataType Delete(int i);

void Print();

private:

Node<DataType>*first;

};

#endif

 

#include<iostream.h>

#include"Student.h"

template<class DataType>

Student<DataType>::Student()

{

first=new Node<DataType>;

first->next=NULL;

}

template<class DataType>

Student<DataType>::Student(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>

Student<DataType>::~Student()

{

Node<DataType>*q=NULL;

while(first!=NULL)

{

q=first;

first=first->next;

delete q;

}

}

template<class DataType>

void Student<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>

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

{

Node<DataType>*p=first->next;

int count=1;

while(p!=NULL)

{

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

p=p->next;

count++;

}

return 0;

}

template<class DataType>

DataType Student<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 Student<DataType>::Print()

{

Node<DataType>*p=first->next;

while(p!=NULL)

{

cout<<p->data<<" ";

p=p->next;

}

cout<<endl;

}


#include<iostream.h>

#include"Student.cpp"

void main()

{

double s[5]={85.5,67,48,91,76};

Student<double>S(s,5);

cout<<"该组学生成绩为:"<<endl;

S.Print();

try

{

S.Insert(3,84);

}

catch(char*s)

{

cout<<s<<endl;

}

cout<<endl;

cout<<"修改后的成绩为:"<<endl;

S.Print();

cout<<endl;

cout<<"成绩为84的位置是:";

cout<<S.Locate(84)<<endl;

cout<<endl;

cout<<"删除前的成绩:"<<endl;

S.Print();

try

{

S.Delete(2);

}

catch(char*s)

{

cout<<s<<endl;

}

cout<<endl;

cout<<"删除后的成绩为:"<<endl;

S.Print();

}

运行结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值