嵌入式第二十六篇——数据结构双向链表

一、基本概念

双向链表是一种常见的数据结构,每个节点包含两个指针,分别指向前驱节点和后继节点。与单向链表相比,双向链表可以从任意节点向前或向后遍历,操作更灵活。

二、节点定义

在C语言中,双向链表的节点通常定义为结构体,包含数据域和两个指针域:

c 复制代码
typedef struct Node {
    int data;           // 数据域
    struct Node *prev;  // 指向前驱节点
    struct Node *next;  // 指向后继节点
} Node;

三、创建双向链表

初始化一个双向链表通常需要创建头节点,并将指针初始化为NULL

c 复制代码
Node* createList() {
    Node *head = (Node*)malloc(sizeof(Node));
    if (head == NULL) {
        printf("内存分配失败\n");
        exit(1);
    }
    head->prev = NULL;
    head->next = NULL;
    return head;
}

四、插入节点

双向链表的插入操作分为头部插入、尾部插入和指定位置插入。

1、头部插入:

c 复制代码
void insertAtHead(Node *head, int data) {
    Node *newNode = (Node*)malloc(sizeof(Node));
    newNode->data = data;
    newNode->prev = NULL;
    newNode->next = head->next;

    if (head->next != NULL) {
        head->next->prev = newNode;
    }
    head->next = newNode;
}

2、尾部插入:

c 复制代码
void insertAtTail(Node *head, int data) {
    Node *newNode = (Node*)malloc(sizeof(Node));
    newNode->data = data;
    newNode->next = NULL;

    Node *current = head;
    while (current->next != NULL) {
        current = current->next;
    }

    current->next = newNode;
    newNode->prev = current;
}

五、删除节点

删除操作需要调整前驱和后继节点的指针:

c 复制代码
void deleteNode(Node *head, int data) {
    Node *current = head->next;
    while (current != NULL) {
        if (current->data == data) {
            if (current->prev != NULL) {
                current->prev->next = current->next;
            }
            if (current->next != NULL) {
                current->next->prev = current->prev;
            }
            free(current);
            return;
        }
        current = current->next;
    }
    printf("未找到该节点\n");
}

六、遍历双向链表

双向链表支持正向和反向遍历:

1、正向遍历:

c 复制代码
void traverseForward(Node *head) {
    Node *current = head->next;
    while (current != NULL) {
        printf("%d ", current->data);
        current = current->next;
    }
    printf("\n");
}

2、反向遍历:

c 复制代码
void traverseBackward(Node *head) {
    Node *current = head;
    while (current->next != NULL) {
        current = current->next;
    }
    while (current != head) {
        printf("%d ", current->data);
        current = current->prev;
    }
    printf("\n");
}
相关推荐
Darling噜啦啦2 天前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
LDR0063 天前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言
通信小呆呆3 天前
当算法有了“五感”:多模态数据融合如何向人体感官协同学习?
人工智能·学习·算法·机器学习·机器人
H__Rick3 天前
自动对焦学习-3
人工智能·学习·计算机视觉
Daisy Lee3 天前
量化学习-第1章-什么是量化金融
学习·金融·datawhale
小小工匠3 天前
Redis - 事务机制:能实现 ACID 属性吗
数据结构·redis·性能优化·并发·持久化
Luminous.3 天前
C语言--day30
c语言·开发语言
Alsn863 天前
等待学习-学习目录:Docker 容器安全攻防
学习·安全·docker
玖玥拾3 天前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
YM52e3 天前
买菜计算器小应用 - HarmonyOS ArkUI 开发实战-PC版本
学习·华为·harmonyos·鸿蒙·鸿蒙系统