循環(huán)鏈表中的最后一個(gè)節(jié)點(diǎn)的指針指向第一個(gè)節(jié)點(diǎn),形成一個(gè)閉環(huán)。可以快速進(jìn)行在頭部或尾部插入和刪除節(jié)點(diǎn)的操作。循環(huán)鏈表可以從任意節(jié)點(diǎn)開始遍歷,可以順時(shí)針或逆時(shí)針遍歷整個(gè)鏈表。
代碼:
#include <stdio.h>
#include <stdlib.h>
// 定義鏈表節(jié)點(diǎn)結(jié)構(gòu)
struct Node {
int data; // 數(shù)據(jù)域
struct Node* next; // 指向下一個(gè)節(jié)點(diǎn)的指針
};
// 初始化循環(huán)鏈表
void initCircularList(struct Node** head) {
*head = NULL; // 將頭指針置為空,表示鏈表為空
}
// 在循環(huán)鏈表末尾添加節(jié)點(diǎn)
void appendCircularNode(struct Node** head, int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
newNode->next = *head; // 將新節(jié)點(diǎn)的next指針指向自身,形成循環(huán)
} else {
struct Node* temp = *head;
while (temp->next != *head) {
temp = temp->next;
}
temp->next = newNode;
newNode->next = *head;
}
}
// 在循環(huán)鏈表指定位置插入節(jié)點(diǎn)
void insertCircularNode(struct Node** head, int data, int position) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
if (position == 0) {
newNode->next = *head;
struct Node* temp = *head;
while (temp->next != *head) {
temp = temp->next;
}
temp->next = newNode;
*head = newNode;
} else {
struct Node* temp = *head;
int count = 0;
while (temp->next != *head && count < position - 1) {
temp = temp->next;
count++;
}
if (count < position - 1) {
printf("Invalid position\n");
return;
}
newNode->next = temp->next;
temp->next = newNode;
}
}
// 刪除循環(huán)鏈表指定位置的節(jié)點(diǎn)
void deleteCircularNode(struct Node** head, int position) {
if (*head == NULL) {
printf("List is empty\n");
return;
}
struct Node* temp = *head;
if (position == 0) {
while (temp->next != *head) {
temp = temp->next;
}
if (temp == *head) {
*head = NULL;
} else {
temp->next = (*head)->next;
*head = (*head)->next;
}
free(temp);
} else {
int count = 0;
struct Node* prev = NULL;
while (temp->next != *head && count < position) {
prev = temp;
temp = temp->next;
count++;
}
if (count < position) {
printf("Invalid position\n");
return;
}
prev->next = temp->next;
free(temp);
}
}
// 打印循環(huán)鏈表
void printCircularList(struct Node* head) {
if (head == NULL) {
printf("List is empty\n");
return;
}
struct Node* temp = head;
do {
printf("%d ", temp->data);
temp = temp->next;
} while (temp != head);
printf("\n");
}
// 釋放循環(huán)鏈表內(nèi)存
void freeCircularList(struct Node* head) {
if (head == NULL) {
return;
}
struct Node* temp = head;
struct Node* nextNode;
do {
nextNode = temp->next;
free(temp);
temp = nextNode;
} while (temp != head);
}
int main() {
struct Node* head;
initCircularList(&head);
// 在循環(huán)鏈表末尾添加節(jié)點(diǎn)
appendCircularNode(&head, 10);
appendCircularNode(&head, 20);
appendCircularNode(&head, 30);