要創建一個雙向循環鏈表,你可以按照以下步驟進行:
typedef struct Node {
int data;
struct Node* prev;
struct Node* next;
} Node;
Node* createDoublyLinkedList() {
Node* head = (Node*)malloc(sizeof(Node));
head->data = 0;
head->prev = head;
head->next = head;
return head;
}
void insertNode(Node* head, int data, int position) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
Node* current = head->next;
int i = 1;
// 找到指定位置的節點
while (current != head && i < position) {
current = current->next;
i++;
}
// 在當前節點之前插入新節點
newNode->prev = current->prev;
newNode->next = current;
current->prev->next = newNode;
current->prev = newNode;
}
void deleteNode(Node* head, int position) {
Node* current = head->next;
int i = 1;
// 找到指定位置的節點
while (current != head && i < position) {
current = current->next;
i++;
}
// 刪除當前節點
current->prev->next = current->next;
current->next->prev = current->prev;
free(current);
}
這樣,你就可以使用上述函數來創建和操作雙向循環鏈表了。記得在使用完鏈表后,釋放內存空間,防止內存泄漏。