#pragma once
/**************Forward Declarations************/
template<class T> class CListNode;
template<class T> class CList;
/
template <class T>
class CListNode
{
public:
T m_data;
CListNode<T> * m_next;
CListNode ()
{
m_next = 0;
}
void InsertAfter(T data);
};
template <class T>
void CListNode<T>::InsertAfter(T data)
{
CListNode<T> * pNode= new CListNode<T>;
pNode->m_data = data;
pNode->m_next = m_next;
m_next= pNode;
}
/
template<class T>
class CList
{
public:
CListNode<T> * m_head;
CListNode<T> * m_tail;
CListNode<T> * m_itr;
unsigned short m_count;
CList()
{
m_head =0;
m_tail = 0;
m_count = 0;
m_itr = 0;
}
~CList();
//member functions
void Destroy();
void Append(T p_data);
void Calibrate(unsigned short);//adjust the iterator by the index
void Modify(unsigned short,T);
void Remove(unsigned short);
void Insert(unsigned short ,T);
void RemoveHead();
void Prepend(T);
void Forth();
T& operator [](unsigned short);//
};
template<class T>
void CList<T>::Destroy()
{
CListNode<T> * itr= m_head;
CListNode<T> * temp;
while(itr) //if there is a node
{
temp = itr->m_next;
delete itr;
itr = temp;
}
m_count = 0;
m_head = 0;
m_tail= 0;
}
template<class T>
void CList<T>::Forth()
{
if(m_itr)
m_itr= m_itr->m_next;
}
template<class T>
void CList<T>::Prepend(T p_data)
{
if(0==m_count)
{
m_head=m_tail= new CListNode<T>;
m_head->m_data = p_data;
++m_count;
}
else
{
CListNode<T> * node = new CListNode<T>;
node->m_data = p_data;
node->m_next = m_head;
m_head = node;
++m_count;
}
}
template<class T>
void CList<T>::Insert(unsigned short index, T p_data)
{
if(0==m_count)
Append(p_data);
else
{
Calibrate(index);
m_itr->InsertAfter(p_data);
++m_count;
if(m_itr==m_tail)
m_tail= m_tail->m_next;
}
}
template<class T>
void CList<T>::RemoveHead()
{
if(0==m_count)
return;
else if(1==m_count)
{
delete m_head;
m_head =m_tail =0;
--m_count;
}
else
{
CListNode<T> * temp = m_head->m_next;
delete m_head;
m_head = temp;
--m_count;
}
}
template<class T>
void CList<T>::Modify(unsigned short index, T p_data)
{
Calibrate(index);
m_itr->m_data=p_data;
}
template<class T>
void CList<T>::Remove(unsigned short index)
{
if(0==index)
RemoveHead();
else
{
Calibrate(index-1);
CListNode<T> * node =m_itr->m_next;
m_itr->m_next= node->m_next;
delete node;
--m_count;
if(m_count==index)
m_tail= m_itr;
}
}
template<class T>
void CList<T>::Calibrate(unsigned short index)
{
m_itr= m_head;
while(index&&m_itr)
{
//may prevent access violation
m_itr = m_itr->m_next;
--index;
}
}
template<class T>
CList<T>::~CList()
{
CListNode<T> * itr= m_head;
CListNode<T> * temp;
while(itr) //if there is a node
{
temp = itr->m_next;
delete itr;
itr = temp;
}
}
template<class T>//
T& CList<T>::operator [](unsigned short index)
{
Calibrate(index);
return m_itr->m_data;
}
template<class T>
void CList<T>::Append(T p_data)
{
if(0==m_count)
{
m_tail = new CListNode<T>;
m_head =m_tail;
m_head->m_data= p_data;
++m_count;
}
else
{
m_tail->InsertAfter(p_data);
m_tail=m_tail->m_next;
++m_count;
}
}