单向循环链表
2012-03-08 19:50
423 查看
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; } }
相关文章推荐
- (C语言版)链表(二)——实现单向循环链表创建、插入、删除、释放内存等简单操作
- 带表头节点的单向循环链表编程
- 如何判断一个单向链表是否存在循环的经典方法
- 循环单向链表
- 单向循环链表的实现
- 大话数据结构四:线性表的链式存储结构(单向循环链表)
- 单向循环链表的实现以及约瑟夫环的实现
- 一步一步写算法(之循环单向链表)
- 数据结构学习系列三-单向循环链表(c++实现且应用模板)
- 单向循环链表
- 链表(单链表,带表头的链表,单向循环链表,双向循环链表)
- ※数据结构※→☆线性表结构(list)☆============单向循环链表 链式存储结构(list circular single)(四)
- c实现逆转单向循环链表
- 单向循环链表
- C++实现单向循环链表
- 有头节点单向循环链表
- 数据结构作业代码保存-2.1 单向循环链表的建立,插入和删除,和指针移动
- 单向循环链表实例
- 带头结点的循环单向链表
- java单向循环链表实现约瑟夫环