在C语言中,双向链表的插入操作可以分为三种情况:在链表的头部插入节点、在链表的中间插入节点和在链表的尾部插入节点。以下是这三种情况的代码示例:
- 在链表的头部插入节点:
void insertAtBeginning(Node **head_ref, int data) { Node *new_node = (Node *) malloc(sizeof(Node)); new_node->data = https://www.yisu.com/ask/data;>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 = https://www.yisu.com/ask/data;>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 = https://www.yisu.com/ask/data;>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; }
这些代码示例展示了如何在双向链表中插入节点。在实际应用中,根据具体情况选择合适的插入方法。