链表4-循环链表
循环链表的特点: 链表的尾结点后继指向头结点
循环链表的结构
typedef struct Node{
int data; //数据域
struct Node *nextNode; //后继
} Node;
循环链表的初始化
Node* initHeader(){
//创建头结点
Node *header = (Node*)malloc(sizeof(Node));
//头结点的数据(用于存储链表长度)
header->data = 0;
//头结点的后继
header->nextNode = header;
//返回
return header;
}
后插法添加元素
//后插法添加元素(返回尾结点)
Node* addNode(Node *header, Node *roar){
//空链表
if(!header){
cout << "链表不存在!" << endl;
return NULL;
}
//开辟空间
Node *newNode = (Node*)malloc(sizeof(Node));
//赋值
cout << "输入值" << endl;
cin >> newNode->data;
newNode->nextNode = NULL;
//尾结点后继指向新结点
roar->nextNode = newNode;
//新结点后继指向header
newNode->nextNode = header;
//更新链表长度
header->data++;
//更新尾结点
return newNode;
}
链表长度
void sizeOfLinkList(Node *header){
//空链表
if(!header){
cout << "链表不存在!" << endl;
return;
}
cout << "链表长度: " << header->data << endl;
}
输出链表
void display(Node *header){
//空链表
if(!header){
cout << "链表不存在!" << endl;
return;
}
Node *curNode = header->nextNode;
while(curNode!=header){
cout << curNode->data << " ";
//前进
curNode = curNode->nextNode;
}
cout << endl;
}
测试
int main(){
int choice;
Node *header=NULL;
Node *roar=NULL;
int length=0;
do{
cout << "--------------" << endl;
cout << "1.创建" << endl;
cout << "2.在尾部插入新节点" << endl;
cout << "3.输出链表" << endl;
cout << "0.退出" << endl;
cout << "输入选项:";
cin >> choice;
switch(choice){
case 1:
header = initHeader();
roar = header;
break;
case 2:
roar = addNode(header, roar, length);
break;
case 3:
display(header);
break;
default:
break;
}
}while(choice!=0);
system("pause");
return 0;
}
标签:Node,结点,cout,nextNode,链表,header,循环
From: https://www.cnblogs.com/HIK4RU44/p/18144049