要實現一個雙向鏈表的數據結構,你可以按照以下步驟進行:
typedef struct Node {
int data;
struct Node* prev;
struct Node* next;
} Node;
typedef struct LinkedList {
Node* head;
Node* tail;
} LinkedList;
void initLinkedList(LinkedList* list) {
list->head = NULL;
list->tail = NULL;
}
void insertNode(LinkedList* list, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->prev = NULL;
newNode->next = NULL;
if (list->head == NULL) {
list->head = newNode;
list->tail = newNode;
} else {
newNode->prev = list->tail;
list->tail->next = newNode;
list->tail = newNode;
}
}
void deleteNode(LinkedList* list, int data) {
Node* current = list->head;
while (current != NULL) {
if (current->data == data) {
if (current->prev != NULL) {
current->prev->next = current->next;
} else {
list->head = current->next;
}
if (current->next != NULL) {
current->next->prev = current->prev;
} else {
list->tail = current->prev;
}
free(current);
return;
}
current = current->next;
}
}
void printLinkedList(LinkedList* list) {
Node* current = list->head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
完成了上述步驟后,你就可以使用這些函數來創建和操作雙向鏈表了。