template<typename DataType> class CircularListNode {//循环链表结点模板 public: friend class CircularList<DataType>; CircularListNode() { m_next = NULL; } CircularListNode(DataType data, CirculatListNode* nextOne = NULL) { m_data = data; m_next = mextOne; } ~CirclarListNode() { m_next = NULL; } private: CircularListNode* m_next; DataType m_data; }; template <typename DataType> class CirculatList {//循环链表模板 public: CircularList() { //CircularList类构造函数 head = new CircularListNode<DataType>(); head->m_next = head; } ~CircularList() { //CircularList类析构函数 cleanUp(); delete head; } void cleanUp();//清空循环链表 int getLength();//获取循环链表的长度 //查询具有value值的第i个元素 并返回其指针 CircularListNode<DataType>* findNode(int i, DataType value); bool insertNode(DataType data);//在链表的尾部插入元素 bool deleteNode(DataType value);//删除具有value值的所有元素 DataType getValue(CircularListNode<DataType>* node);//获取指定元素的值 private: CircularListNode<DataType>* head; }; template <typename DataType> void CircularList<DataType>::cleanUp() { CircularListNode* p; //设置删除结点的游标指针 while(head->m_next != head) { p= head->m_next; //初始化指示指针 head->m_next = p->m_next; //将头指针指向下一个结点的下一个结点 delete p; } } template <typename DataType> int CircularList<DataType>::getLength() { int length = 0; CircularListNode<DataType>* p = head; //设置游标指针 while(p->m_next != head) { //游走指针,直至指向头指针时结束 p = p->m_next; length++; } return length; } template <typename DataType> CircularListNode<DataType>* CircularList<DataType>::findNode(int i, DatatType value) { int count = 0; CircularListNode<DataType>* p = head; //游标指针 while(count != 1) { //遍历链表, 寻找值与value相等的结点 p = p->m_next; if(p->m_data == value) {count++;} if(p == head) return NULL; } return p; } template <typename DataType> bool CircularLisr<DataType>::insertNode(DataType data) { CircularListNode<DataType>* p = head; //游标指针 CircularListNode<DataType>* node = new CircularListNode<DataType>(data, NULL); //建立新结点 if(node == NULL) return false; // 如果新结点空间分配失败 就返回false //寻找尾结点 while(p->m_next != head) {p= p->m_next;} //寻找结点位置 node->m_next = p->m_next; //插入新结点 p->m_next = node; return true; } template <typename DataType> bool CircularList<DataType>::deleteNode(DataType value) { int count = 0;//删除的结点数 CirCularListNode<DataType>* p = head->m_next, * l = head;//设置游标指针 while(p != head) { if(p->m_data == value) { //如果结点值与value相等 l->m_next = p->m_next; //删除该结点并计数 delete p; count++; p= l->m_next; } else { l = p; p = p->m_next; } } if(count == 0) return false; else return true; } template <typename DataType> DataType CircularList<DataType>::getValue(CircularListNode<DataType>* node) { return node->m_data; }
主函数部分自己写吧
时间: 2024-11-21 02:58:55