// .hpp文件
#include <stdio.h>
class NodeCList{
public:
NodeCList();
static NodeCList* create(int element);
int element;
NodeCList* next;
};
class CircleList {
public:
CircleList();
static CircleList* create();
void append(NodeCList* node);
void insertAtFirst(NodeCList* node);
void insert(NodeCList* node, int index);
NodeCList* find(int index);
int find(NodeCList* node);
void remove(int index);
void clear();
void printContent();
public:
NodeCList* rear;
int length;
};
//.cpp文件
NodeCList:: NodeCList():next(nullptr){
}
NodeCList* NodeCList::create(int element){
auto node = new (std::nothrow) NodeCList();
node->element = element;
return node;
}
CircleList::CircleList():rear(nullptr),length(0){
}
CircleList* CircleList::create(){
return new(std::nothrow) CircleList();
}
void CircleList::append(NodeCList *node){
if (!node) return;
if (!this->rear){
this->rear = node;
node->next = this->rear;
} else{
node->next = this->rear->next;
this->rear->next = node;
this->rear = node;
}
this->length ++;
}
void CircleList::insertAtFirst(NodeCList *node){
if (this->length == 0){
this->rear = node;
node->next = this->rear;
} else{
node->next = this->rear->next;
this->rear->next = node;
}
this->length ++;
}
void CircleList::insert(NodeCList *node, int index){
if (index < 0 || index > this->length){
CCLOG("index error.");
return;
}
if (index == 0){
this->insertAtFirst(node);
} else if (index == this->length){
this->append(node);
} else{
auto tmp = this->find(index - 1);
node->next = tmp->next;
tmp->next = node;
this->length ++;
}
}
NodeCList* CircleList::find(int index){
if (index < 0 || index > this->length - 1){
CCLOG("index error.");
return nullptr;
}
auto temp = this->rear->next;
for (int i = 0; i < index; i++){
temp = temp->next;
}
return temp;
}
int CircleList::find(NodeCList *node){
auto tmp = this->rear->next;
for (int i = 0; i < this->length; i++){
if (node->element == tmp->element){
return i;
}
tmp = tmp->next;
}
return -1;
}
void CircleList::remove(int index){
if (index < 0 || index > this->length - 1 || this->length == 0) {
CCLOG("index error.");
return;
}
if (this->length == 1){
this->clear();
}
if (index == 0){
this->rear->next = this->find(0)->next;
this->length --;
} else{
this->find(index - 1)->next = this->find(index)->next;
this->length --;
}
}
void CircleList::printContent(){
std::string str = "";
auto temp = this->rear->next;
for (int i = 0; i < this->length; i++){
printf("第%d个为: %d", i, temp->element);
printf("\n");
temp = temp->next;
}
}
void CircleList::clear(){
this->length = 0;
this->rear = nullptr;
}
C++循环链表的实现
最新推荐文章于 2022-09-22 11:00:03 发布