⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mylist.h

📁 自己做的小编译程序,大家看看好不好用哦,是词法分析器
💻 H
字号:
#ifndef H_LIST_INCLUDED
#define H_LIST_INCLUDED

#include <stdio.h>

template<class T>
struct Node
{
	T data;
	Node<T>* next;
	Node() : next(NULL) {}
};

template<class T>
class CMyList
{
public:
	CMyList();
	CMyList(const CMyList<T>&);
	~CMyList();

public:
	int Size();
	Node<T>* GetHead();
	Node<T>* GetTail();

	Node<T>* GetNode(int);
	Node<T>* GetFirstNode(const T&);
	Node<T>* InsertAtHead(const T&);
	Node<T>* InsertAtTail(const T&);
	bool DeleteNode(int);

public:
	CMyList<T>& operator=(const CMyList<T>&);

private:
	int nCount;
	Node<T>*  head;
	Node<T>*  tail;
};

template<class T>
CMyList<T>::CMyList()
: head(NULL),
  tail(NULL)
{
	nCount = 0;
}

template<class T>
CMyList<T>::CMyList(const CMyList<T>& t)
{
	nCount = 0;
	head = tail = NULL;
	Node<T>* ptr = t.head;

	while(ptr)
	{
		InsertAtTail(ptr->data);
		ptr = ptr->next;
	}
}

template<class T>
CMyList<T>::~CMyList()
{
	while (head != NULL)
	{
		Node<T>* ptr = head;
		head = head->next;
		delete ptr;
	}
}

template<class T>
int CMyList<T>::Size()
{
	return nCount;
}

template<class T>
Node<T>* CMyList<T>::GetHead()
{
	return head;
}

template<class T>
Node<T>* CMyList<T>::GetTail()
{
	return tail;
}

template<class T>
Node<T>* CMyList<T>::GetNode(int index)
{
	if (index >= nCount || index < 0) return NULL;

	Node<T>* ptr = head;
	for (int i = 0; i < index; i++)
	{
		ptr = ptr->next;
	}

	return ptr;
}

template<class T>
Node<T>* CMyList<T>::GetFirstNode(const T& data)
{
	Node<T>* ptr = head;
	while (ptr != NULL)
	{
		if (ptr->data == data) break;
		ptr = ptr->next;
	}
	return ptr;
}

template<class T>
Node<T>* CMyList<T>::InsertAtHead(const T& data)
{
	Node<T>* node = new Node<T>;
	node->data = data;
	node->next = NULL;

	if (head == NULL)
	{
		head = tail = node;
	}
	else
	{
		node->next = head;
		head = node;
	}
	++nCount;

	return node;
}

template<class T>
Node<T>* CMyList<T>::InsertAtTail(const T& data)
{
	Node<T>* node = new Node<T>;
	node->data = data;
	node->next = NULL;

	if (head == NULL)
	{
		head = tail = node;
	}
	else
	{
		tail->next = node;
		tail = node;
	}
	++nCount;

	return node;
}

template <class T>
bool CMyList<T>::DeleteNode(int index)
{
	if (index >= nCount || index < 0) return false;

	if (nCount == 1)
	{
		delete head;
		head = tail = NULL;
	}
	else
	{		
		Node<T>* ptr = head;
		for (int i = 0; i < index - 1; i++)
		{
			ptr = ptr->next;
		}
		Node<T>* temp = ptr->next;
		ptr->next = temp->next;
		delete temp;
	}
	--nCount;

	return true;
}

template <class T>
CMyList<T>& CMyList<T>::operator=(const CMyList<T>& t)
{
	nCount = 0;
	head = tail = NULL;
	Node<T>* ptr = t.head;

	while(ptr)
	{
		InsertAtTail(ptr->data);
		ptr = ptr->next;
	}

	return *this;
}

#endif // H_LIST_INCLUDED

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -