template <typename T>
class CircleListNode
{
T data;
CircleListNode<T> *next;
public:
CircleListNode():next(NULL){}
CircleListNode(T value):data(value),next(NULL){}
T& GetData()
{
return data;
}
CircleListNode<T>* GetNext() const
{
return next;
}
void SetNext(CircleListNode<T> *pnext)
{
next = pnext;
}
};
template <typename T>
class CircleList
{
public:
CircleList()
{
// 创建表头结点
head = tail = new CircleListNode<T>;
current = NULL;
head->SetNext(head);
}
~CircleList()
{
RemoveAll();
// 释放头结点
if(head)
{
delete head;
head = tail = current = NULL;
}
}
void SetBegin(); // 置current到表头
int GetCount(); // 注意防止死循环
void RemoveThis();
void RemoveAll();
bool AddTail(T data);
CircleListNode<T> * GetCurrent();
bool IsEmpty();
//返回当前指针的值,并使指针向后移动一位
T& GetCurrentDataAndRemoveNext();
// 返回第index位置上的数据
T& GetAt(int index);
private:
CircleListNode<T> *head;
CircleListNode<T> *tail;
CircleListNode<T> *current;
};
template <typename T> T& CircleList<T>::GetAt(int index)
{
SetBegin();
while(index)
{
GetCurrentDataAndRemoveNext();
index--;
}
return current->GetData();
}
template <typename T> T& CircleList<T>::GetCurrentDataAndRemoveNext()
{
// 跳过头结点
if(current == head)
{
current = current->GetNext();
}
T data = current->GetData();
current = current->GetNext();
return data;
}
template <typename T> bool CircleList<T>::IsEmpty()
{
return head->GetNext() == head;
}
template <typename T> CircleListNode<T> * CircleList<T>::GetCurrent()
{
return current;
}
template <typename T> void CircleList<T>::SetBegin()
{
current = head;
}
template <typename T> int CircleList<T>::GetCount()
{
int total = 0;
CircleListNode<T> *pnow = current;
while(pnow->GetNext() != current)
{
++total;
pnow = pnow->GetNext();
}
return total;
}
template <typename T> void CircleList<T>::RemoveThis()
{
// 处理好表头
if(current == head)
{// 表头不能被删除,向后移动一个结点
current = current->GetNext();
}
CircleListNode<T> *prev = current; // 寻找current的前一个结点
for(int i=0; i<GetCount(); i++)
{
prev=prev->GetNext();
}
// 删除
prev->SetNext(current->GetNext());
delete current;
// 当前指针向后移动一个位子
current = prev->GetNext();
}
template <typename T> void CircleList<T>::RemoveAll()
{
SetBegin(); // 从第一个开始
int len = GetCount();
for(int i=0; i< len; i++)
{
RemoveThis();
}
current = head; // 注意,删除后要重置当前结点
}
template <typename T> bool CircleList<T>::AddTail(T data)
{
CircleListNode<T> *pnode = new CircleListNode<T>(data);
tail->SetNext(pnode);
tail = tail->GetNext();
tail->SetNext(head); // 指向头结点
if(tail != NULL)
{
return true;
}
else
{
return false;
}
}
单向循环链表
最新推荐文章于 2020-01-30 20:28:47 发布