实验3:单链表

#include <iostream>
using namespace std;

template<class datatype>
struct Node
{
	datatype data;        //数据域
	Node<datatype> *next;          //指针域
};

template<class datatype>
class scorelist
{
private:
	Node<datatype> *first;         //头指针
public:
	scorelist()
	{
		first = new Node<datatype>;            //生成头结点
		first->next = NULL;          //制空
	}
	scorelist(datatype a[], int n);
	~scorelist();
	datatype get(int x);
	void insert(int i, datatype x);
	void printlist();
};

template<class datatype>
datatype scorelist<datatype>::get(int x)
{
	Node<datatype> *p = first->next;
	int count = 1;
	while (p != NULL)
	{
		if (p->data == x)
			return count;
		p = p->next;
		count++;
	}
}

template<class datatype>
scorelist<datatype>::scorelist(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>
scorelist<datatype>::~scorelist()
{
	Node<datatype> *q = NULL;
	while (first != NULL)
	{
		q = first;
		first = first->next;
		delete q;
	}
}

template<class datatype>
void scorelist<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>
void scorelist<datatype>::printlist()
{
	Node<datatype> *p = first->next;
	while (p != NULL)
	{
		cout << p->data << " ";
		p = p->next;
	}
	cout << endl;
}

void main()
{
	int stu[6] = { 70,85,96,91,81,99 };
	scorelist<int>student(stu,6);
	cout << "输出成绩:" << endl;
	student.printlist();
	try
	{
		student.insert(3,94);
	}
	catch (char *s)
	{
		cout << s << endl;
	}
	cout << "插入成绩后的列表:" << endl;
	student.printlist();
	cout << "第四个人的成绩:" << endl;
	cout << student.get(4)<<endl;
}

猜你喜欢

转载自blog.csdn.net/u011633428/article/details/80173031