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

一、基本概念

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

二、节点定义

在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");
}
相关推荐
2601_949146533 小时前
C语言语音通知接口接入教程:如何使用C语言直接调用语音预警API
c语言·开发语言
ValhallaCoder3 小时前
hot100-二叉树I
数据结构·python·算法·二叉树
执笔论英雄3 小时前
【大模型学习cuda】入们第一个例子-向量和
学习
wdfk_prog3 小时前
[Linux]学习笔记系列 -- [drivers][input]input
linux·笔记·学习
月挽清风5 小时前
代码随想录第十五天
数据结构·算法·leetcode
知南x5 小时前
【Ascend C系列课程(高级)】(1) 算子调试+调优
c语言·开发语言
NEXT065 小时前
前端算法:从 O(n²) 到 O(n),列表转树的极致优化
前端·数据结构·算法
Gary Studio6 小时前
rk芯片驱动编写
linux·学习
mango_mangojuice6 小时前
Linux学习笔记(make/Makefile)1.23
java·linux·前端·笔记·学习
lingggggaaaa6 小时前
安全工具篇&动态绕过&DumpLsass凭据&Certutil下载&变异替换&打乱源头特征
学习·安全·web安全·免杀对抗