使用C语言实现双链表的基本操作

#include <stdio.h>
#include <stdlib.h>

// 双链表节点结构
struct Node {
    int data;
    struct Node* prev;  // 前驱节点指针
    struct Node* next;  // 后继节点指针
};

// 在双链表的头部插入一个元素
void insertAtHead(struct Node** head, int data) {
    // 创建新节点
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = data;
    
    // 链接新节点
    newNode->prev = NULL;
    newNode->next = *head;
    
    // 更新头指针
    if (*head != NULL) {
        (*head)->prev = newNode;
    }
    *head = newNode;
}

// 在双链表的尾部插入一个元素
void insertAtTail(struct Node** head, int data) {
    // 创建新节点
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = data;
    newNode->next = NULL;
    
    // 若链表为空则直接插入
    if (*head == NULL) {
        newNode->prev = NULL;
        *head = newNode;
        return;
    }
    
    // 找到链表尾部节点
    struct Node* tail = *head;
    while (tail->next != NULL) {
        tail = tail->next;
    }
    
    // 链接新节点
    tail->next = newNode;
    newNode->prev = tail;
}

// 在双链表中删除一个指定元素
void deleteNode(struct Node** head, int data) {
    // 若链表为空则直接返回
    if (*head == NULL) {
        return;
    }
    
    // 找到要删除的节点
    struct Node* curr = *head;
    while (curr != NULL && curr->data != data) {
        curr = curr->next;
    }
    
    // 若未找到则直接返回
    if (curr == NULL) {
        return;
    }
    
    // 更新链表链接
    if (curr->prev != NULL) {
        curr->prev->next = curr->next;
    } else {
        *head = curr->next;
    }
    if (curr->next != NULL) {
        curr->next->prev = curr->prev;
    }
    
    // 释放节点内存
    free(curr);
}

// 打印双链表所有元素
void printList(struct Node* head) {
    struct Node* curr = head;
    while (curr != NULL) {
        printf("%d ", curr->data);
        curr = curr->next;
    }
    printf("\n");
}

// 主函数
int main() {
    struct Node* head = NULL;
    
    // 在双链表头部插入元素
    insertAtHead(&head, 5);
    insertAtHead(&head, 10);
    insertAtHead(&head, 15);
    printf("双链表头部插入之后的结果: ");
    printList(head);
    
    // 在双链表尾部插入元素
    insertAtTail(&head, 20);
    insertAtTail(&head, 25);
    printf("双链表尾部插入之后的结果: ");
    printList(head);
    
    // 删除双链表中的元素
    deleteNode(&head, 10);
    printf("删除元素10后的结果: ");
    printList(head);
    
    return 0;
}

 

posted @ 2023-07-03 22:58  nullIsland01  阅读(84)  评论(0)    收藏  举报