要实现一个双向链表的数据结构,你可以按照以下步骤进行:
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");
}
完成了上述步骤后,你就可以使用这些函数来创建和操作双向链表了。