?? mylist.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 + -