C++模板类实现LinkList

LinkList.h文件

#pragma once
#include 
//在插入元素时,应该把每一个元素都保存下来
//模板类中应该能分配节点,缓存节点

template 
struct Node
{
	T t;
	Node *next;
};

template 
class LinkList
{
public:
	LinkList(void);
	~LinkList(void);

	int clear();
	int getLen();
	int insert(T &t,int pos);
	int get(int pos,T &t);
	int del(int pos,T &t);

private:
	Node *head;//头结点,指向链表
	int len;
};

LinkList.cpp文件

#include "LinkList.h"

template 
LinkList::LinkList(void)
{
	head = new Node;//建立一个带有头结点的链表
	head->next = NULL;
	len = 0;
}


template 
LinkList::~LinkList(void)
{
	Node *tem = NULL;

	while(head != NULL)
	{
		tem = head->next;
		delete head;
		head = tem;
	}
	len = 0;
	head = NULL;
}

template 
int LinkList::clear()
{
	Node *tem = NULL;

	while(head != NULL)
	{
		tem = head->next;
		delete head;
		head = tem;
	}

	head = new Node;//建立一个带有头结点的链表
	head->next = NULL;
	len = 0;

	return 0;
}

template 
int LinkList::getLen()
{
	return len;
}

template 
int LinkList::insert(T &t,int pos)
{
	Node* current = NULL;
	current = head;

	for (int i=0;inext;
	}

	Node* node = new Node;
	if (node == NULL)
	{
		return -1;
	}
	node->t = t;
	node->next = current->next;
	current->next = node;

	len++;

	return 0;
}

template 
int LinkList::get(int pos,T &t)
{
	Node *current = NULL;
	current = head;

	for (int i=0;inext;
	}

	t = current->next->t;

	return 0;
}

template 
int LinkList::del(int pos,T &t)
{
	Node *current = NULL;
	Node *node = NULL;
	current = head;

	for (int i=0;inext;
	}
	node = current->next;
	t = node->t;
	current->next = node->next;

	len--;

	delete node;//插入时new Node需释放

	return 0;
}

main.cpp

#include "LinkList.cpp"

using namespace std;
struct Teacher
{
	int age;
	char name[64];
};

int main()
{
	Teacher t1,t2,t3,t4,tem;
	t1.age = 31;
	t2.age = 32;
	t3.age = 33;

	LinkList list;
	list.insert(t1,0);
	list.insert(t2,0);
	list.insert(t3,0);

	for(int i=0;i < list.getLen();i++)
	{
		list.get(i,tem);
		cout << tem.age << " ";
	}
	cout << endl;

	while(list.getLen() > 0)
	{
		list.del(0,tem);
		cout << tem.age << " ";
	}
	cout << endl;

	list.clear();

	list.insert(t1,0);
	list.insert(t2,0);
	list.insert(t3,0);

	while(list.getLen() > 0)
	{
		list.del(0,tem);
		cout << tem.age << " ";
	}
	cout << endl;


	system("pause");
	return 0;
}

输出结果:

C++模板类实现LinkList_第1张图片

你可能感兴趣的:(数据结构)