数据结构(六)——循环链表
一、循序链表简介
1、循环链表的定义
循环链表的任意元素都有一个前驱和一个后继,所有数据元素在关系上构成逻辑上的环。
循环链表是一种特殊的单链表,尾结点的指针指向首结点的地址。
循环链表的逻辑关系图如下:
2、循环链表的设计实现
循环链表的设计实现要点:
A、通过模板定义CircleList,继承自LinkedList
B、定义连接链表首尾的内部函数
C、实现首元素的插入和删除操作
D、重写清空操作和遍历操作
3、循环链表的实现关键
A、插入位置为0时,头结点和尾结点均指向新结点,新结点作为首结点插入链表。
B、删除位置为0时,头结点和尾结点指向位置为1的结点,删除销毁首结点
二、循环链表的操作
1、尾结点获取
Node* last()
{
return this->position(this->m_length - 1)->next;
}
2、首尾结点连接
void lastToFirst()
{
last()->next = this->m_header.next;
}
三、循环链表的实现
template <typename T>
class CircleList:public LinkedList<T>
{
protected:
typedef typename LinkedList<T>::Node Node;
//尾结点
Node* last()
{
return this->position(this->m_length - 1)->next;
}
//链接最后一个结点和首结点
void lastToFirst()
{
last()->next = this->m_header.next;
}
int mod(int index)const
{
return (this->m_length == 0)?0:(index % this->m_length);
}
public:
bool insert(int index, const T& value)
{
bool ret =