学生成绩链表

#include<iostream.h>
template<class T>
struct Node
{
	T data;
	Node<T>*next;
};
template<class T>
class Student
{
	public:
		Student();
		Student(T a[],int n);
		~Student();
		int Locate(T x);
		void Insert(int i,T x);
		T Delete(int i);
		void Print();
	private:
		Node<T>*first;
};
template<class T>
Student<T>::Student()
{
	first=new Node<T>;
	first->next=NULL;
}
template<class T>
Student<T>::Student(T a[],int n)
{
	Node<T> *r,*s;
	first=new Node<T>;
	r=first;
	for(int i=0;i<n;i++)
	{
		s=new Node<T>;
		s->data=a[i];
		r->next=s;r=s;
	}
	r->next=NULL;
}
template<class T>
Student<T>::~Student()
{
	Node<T> *q=NULL;
	while(first!=NULL)
	{
		q=first;
		first=first->next;
		delete q;
	}
}
template<class T>
void Student<T>::Insert(int i,T x)
{
	Node<T>*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<T>;s->data=x;
		s->next=p->next;p->next=s;
	}
}
template<class T>
T Student<T>::Delete(int i)
{
	Node <T>*p=first,*q=NULL;
	T 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 T>
int Student<T>::Locate(T x)
{
	Node<T> *p=first->next;
	int count=1;
	while(p!=NULL)
	{
		if(p->data==x)return count;
		p=p->next;
		count++;
	}
	return 0;
}
template<class T>
void Student<T>::Print()
{
	Node<T>*p=first->next;
	while(p!=NULL)
	{
		cout<<p->data<<" ";
		p=p->next;
	}
	cout<<endl;
}
void main()
{
	float r[5]={91,92,93,94,95};
	Student<float>L(r,5);
	cout<<"一共有5位学生成绩"<<endl;
	L.Print();
	cout<<"在第3位插入一个分数为100的学生"<<endl;
	L.Insert(4,100);
	cout<<"插入后一共有6位学生成绩"<<endl;
	L.Print();
	cout<<"分数为93的学生位置为";
	cout<<L.Locate(93)<<endl;
	cout<<"执行删除第二个学生分数的操作,删除前数据为:"<<endl;
	L.Print();
	L.Delete(2);
	cout<<"删除后数据为:"<<endl;
	L.Print();
}

运行结果


猜你喜欢

转载自blog.csdn.net/weixin_41936498/article/details/80231585