与单链表相似,先施工创建、尾插法、打印
注意判断尾部等于头节点
#include <iostream>
using namespace std;
typedef struct listNode {
int data;
struct listNode* next;
}LinkNode, LinkList;
bool initLoopLink(LinkList* &list) {
list = new LinkNode;
if (!list) {
return false; //生成失败
}
list->next = list;
list->data = -1;
return true;
}
bool backLoopInsert(LinkList*& list, LinkNode* node) { //尾插法
if (!list || !node) return false;
LinkNode* temp = list;
temp = list->next;
if (list == list->next) { //空循环列表
node->next = list;
list->next = node;
}
else {
while (temp->next != list) { //定位到最后一个节点
temp = temp->next;
}
node->next = temp->next;
temp->next = node;
}
return true;
}
bool listLoopPrint(LinkList* &list) {
LinkNode* p = list->next;
if (!list) cout << "链表为空";
while (p != list) {
cout << p->data << "\t";
p = p->next;
}
cout << endl;
return true;
}
int main(void) {
LinkList* L = NULL;
LinkNode* node;
if (initLoopLink(L)) {
cout << "成功" << endl;
}
else {
exit(-1);
};
cout << "添加十个元素"<<endl;
int num = 0;
//cin >> num;
while ((++num) <= 10) {
node = new LinkNode;
node->data = num;
node->next = NULL;
if (backLoopInsert(L, node)) {
cout << "插入成功" << endl;
}
else {
cout << "插入失败" << endl;
}
}
listLoopPrint(L);
system("pause");
return 0;
}