温馨提示×

c语言双向链表如何插入节点

小樊
111
2024-07-08 19:36:23
栏目: 编程语言

在C语言中,双向链表的插入操作可以分为三种情况:在链表的头部插入节点、在链表的中间插入节点和在链表的尾部插入节点。以下是这三种情况的代码示例:

  1. 在链表的头部插入节点:
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;
}
  1. 在链表的中间插入节点:
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;
    }
}
  1. 在链表的尾部插入节点:
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;
}

这些代码示例展示了如何在双向链表中插入节点。在实际应用中,根据具体情况选择合适的插入方法。

0