C语言_单链表

cpp 复制代码
#include <stdio.h>
#include <stdlib.h>

// 链表节点的结构体定义
typedef struct Node {
    int data;           // 数据域
    struct Node* next;  // 指针域,指向下一个节点//创建第2个结构体时struct Node* next调用上一个的地址 
} Node;

// 创建一个新的节点
Node* createNode(int data) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    if (newNode == NULL) {
        exit(-1); // 内存分配失败,退出程序
    }
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

// 在链表头部插入一个节点
void insertAtHead(Node** head, int data) {
    Node* newNode = createNode(data);
    newNode->next = *head;
    *head = newNode;
}

// 在链表尾部插入一个节点
void insertAtTail(Node** head, int data) {
    Node* newNode = createNode(data);
    if (*head == NULL) {
        *head = newNode;
        return;
    }
    Node* temp = *head;
    while (temp->next != NULL) {
        temp = temp->next;
    }
    temp->next = newNode;
}

// 删除链表中指定数据的节点
void deleteNode(Node** head, int data) {
    if (*head == NULL) return;

    Node* temp = *head;
    Node* prev = NULL;

    if (temp != NULL && temp->data == data) {
        *head = temp->next;
        free(temp);
        return;
    }

    while (temp != NULL && temp->data != data) {
        prev = temp;
        temp = temp->next;
    }

    if (temp == NULL) return;

    prev->next = temp->next;
    free(temp);
}

// 打印链表
void printList(Node* node) {
    while (node != NULL) {
        printf("%d -> ", node->data);
        node = node->next;
    }
    printf("NULL\n");
}

// 释放链表内存
void freeList(Node* node) {
    Node* temp;
    while (node != NULL) {
        temp = node;
        node = node->next;
        free(temp);
    }
}

int main() {
    Node* head = NULL;

    // 插入节点
    insertAtTail(&head, 1);
    insertAtTail(&head, 2);
    insertAtTail(&head, 3);
    insertAtHead(&head, 0);

    // 打印链表
    printList(head);

    // 删除节点
    deleteNode(&head, 2);

    // 再次打印链表
    printList(head);

    // 释放链表内存
    freeList(head);
    head = NULL;

    return 0;
}

重点语句解释

1

typedef struct Node {

int data; // 数据域

struct Node* next ; // 指针域,指向下一个节点//创建第2个结构体时struct Node* next调用上一个结构体的地址

} Node;malloc

2

malloc() : 这是C标准库中的一个函数,用于动态内存分配。它会返回一个指向所请求大小字节的未初始化的内存的指针,或者在无法分配内存时返回 NULL。

相关推荐
_殊途1 小时前
《Java HashMap底层原理全解析(源码+性能+面试)》
java·数据结构·算法
倔强青铜33 小时前
苦练Python第18天:Python异常处理锦囊
开发语言·python
u_topian4 小时前
【个人笔记】Qt使用的一些易错问题
开发语言·笔记·qt
珊瑚里的鱼4 小时前
LeetCode 692题解 | 前K个高频单词
开发语言·c++·算法·leetcode·职场和发展·学习方法
AI+程序员在路上4 小时前
QTextCodec的功能及其在Qt5及Qt6中的演变
开发语言·c++·qt
xingshanchang4 小时前
Matlab的命令行窗口内容的记录-利用diary记录日志/保存命令窗口输出
开发语言·matlab
Risehuxyc4 小时前
C++卸载了会影响电脑正常使用吗?解析C++运行库的作用与卸载后果
开发语言·c++
AI视觉网奇4 小时前
git 访问 github
运维·开发语言·docker
不知道叫什么呀5 小时前
【C】vector和array的区别
java·c语言·开发语言·aigc
liulilittle5 小时前
.NET ExpandoObject 技术原理解析
开发语言·网络·windows·c#·.net·net·动态编程