連結串列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;
}