要實(shí)現(xiàn)一個(gè)雙向鏈表的數(shù)據(jù)結(jié)構(gòu),你可以按照以下步驟進(jìn)行:
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");
}
完成了上述步驟后,你就可以使用這些函數(shù)來(lái)創(chuàng)建和操作雙向鏈表了。