//DynaList.h
#ifndef DYNALIST_H
#define DYNALIST_H
template<class T>
class DynaList
{
public:
DynaList();
~DynaList();
public:
//增加一个节点
int Add(T objSrc);
T& operator[](int nIndex);
int Size();
private:
struct tagNode
{
//加入链表的对象
T t;
//是否第一次被初始化
bool bFirst;
//节点索引值
int nIndex;
//下一个节点指针
tagNode* pNext;
//前一格节点指针
tagNode* pBefore;
};
private:
//节点临时指针
tagNode* m_pTem;
//链表的头指针
tagNode* m_pHead;
//新节点指针
tagNode* m_pNew;
int m_nSize;
};
#endif
//DynaList.cpp
#include "DynaList.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
using namespace std;
template<class T>
DynaList<T>::DynaList()
{
//初始化数据
m_pHead = NULL;
m_pNew = NULL;
m_pHead = new tagNode;
m_pHead->nIndex = -1;
m_pHead->bFirst = true;
m_pHead->pBefore = NULL;
m_pHead->pNext = NULL;
m_nSize = 0;
}
//增加节点
template<class T>
int DynaList<T>::Add(T objSrc)
{
//设置一个遍历的指针
m_pTem = m_pHead;
//将遍历指针移到最后一个节点
while(m_pTem->pNext != NULL)
{
m_pTem = m_pTem->pNext;
}
//新节点的处理
m_pNew = new tagNode;
m_pNew->pBefore = m_pTem;
m_pNew->pNext = NULL;
m_pNew->bFirst = true;
m_pNew->nIndex = m_pTem->nIndex + 1;
//内容复制
memcpy(&m_pNew->t,&objSrc,sizeof(objSrc));
m_pTem->pNext = m_pNew;
//得到首节点
m_pHead = m_pTem;
++m_nSize;
return m_pNew->nIndex;
}
template<class T>
int DynaList<T>::Size()
{
return m_nSize;
}
template<class T>
T& DynaList<T>::operator[](int nIndex)
{
if (nIndex < 0)
{
throw exception("It is not index!");
}
if (nIndex > m_nSize - 1)
{
throw exception("It is out of the range!");
}
while(m_pHead->pNext != NULL)
{
if (m_pHead->nIndex == nIndex)
{
return m_pHead->t;
}
m_pHead = m_pHead->pNext;
}
return m_pHead->t;
}
template<class T>
DynaList<T>::~DynaList()
{
while(m_pHead->pNext != NULL)
{
m_pHead = m_pHead->pNext;
}
//将节点一个一个释放掉
while(m_pHead->pBefore != NULL)
{
tagNode* pTem = m_pHead;
m_pHead = m_pHead->pBefore;
delete pTem;
}
}