C语言实现经典数据结构代码---链表

链表介绍

链表是一种常见的线性数据结构,它由一系列节点组成,每个节点包含数据和指向下一个节点的指针。链表中的节点可以在内存中不连续地分布,通过指针将它们串联起来。

链表的实现原理

节点定义:首先定义一个节点结构体,包含两个成员变量:数据和指向下一个节点的指针。

typedef struct Node {
    int data;
    struct Node* next;
} Node;

 创建节点:通过动态内存分配,使用malloc()函数创建一个新的节点,并初始化数据和指针。

Node* createNode(int data) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

插入节点:在链表中插入一个节点,需要找到插入位置的前一个节点,然后将新节点的指针指向前一个节点的下一个节点,再将前一个节点的指针指向新节点。

void insertNode(Node** head, int data) {
    Node* newNode = createNode(data);
    if (*head == NULL) {
        *head = newNode;
    } else {
        Node* current = *head;
        while (current->next != NULL) {
            current = current->next;
        }
        current->next = newNode;
    }
}

删除节点:在链表中删除一个节点,需要找到要删除节点的前一个节点,然后将前一个节点的指针指向要删除节点的下一个节点,最后释放要删除节点的内存。

void deleteNode(Node** head, int data) {
    Node* current = *head;
    Node* previous = NULL;
    while (current != NULL && current->data != data) {
        previous = current;
        current = current->next;
    }
    if (current == NULL) {
        return;
    }
    if (previous == NULL) {
        *head = current->next;
    } else {
        previous->next = current->next;
    }
    free(current);
}

遍历链表:通过指针依次遍历链表中的每个节点,并输出节点的数据。

void printList(Node* head) {
    Node* current = head;
    while (current != NULL) {
        printf("%d ", current->data);
        current = current->next;
    }
}

链表的优点

链表的优点是插入和删除节点的时间复杂度为O(1),而不会像数组一样需要移动其他元素。但是链表的缺点是访问某个节点需要遍历整个链表,时间复杂度为O(n)。

猜你喜欢

转载自blog.csdn.net/L888666Q/article/details/131414090