在C語言中,雙向鏈表的插入操作可以分為三種情況:在鏈表的頭部插入節點、在鏈表的中間插入節點和在鏈表的尾部插入節點。以下是這三種情況的代碼示例:
void insertAtBeginning(Node **head_ref, int data) {
Node *new_node = (Node *) malloc(sizeof(Node));
new_node->data = data;
new_node->prev = NULL;
new_node->next = *head_ref;
if (*head_ref != NULL) {
(*head_ref)->prev = new_node;
}
*head_ref = new_node;
}
void insertAfter(Node *prev_node, int data) {
if (prev_node == NULL) {
printf("The given previous node cannot be NULL");
return;
}
Node *new_node = (Node *) malloc(sizeof(Node));
new_node->data = data;
new_node->prev = prev_node;
new_node->next = prev_node->next;
prev_node->next = new_node;
if (new_node->next != NULL) {
new_node->next->prev = new_node;
}
}
void insertAtEnd(Node **head_ref, int data) {
Node *new_node = (Node *) malloc(sizeof(Node));
Node *last = *head_ref;
new_node->data = data;
new_node->next = NULL;
if (*head_ref == NULL) {
new_node->prev = NULL;
*head_ref = new_node;
return;
}
while (last->next != NULL) {
last = last->next;
}
last->next = new_node;
new_node->prev = last;
}
這些代碼示例展示了如何在雙向鏈表中插入節點。在實際應用中,根據具體情況選擇合適的插入方法。