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。

相关推荐
小马学嵌入式~19 小时前
嵌入式 SQLite 数据库开发笔记
linux·c语言·数据库·笔记·sql·学习·sqlite
索迪迈科技19 小时前
java后端工程师进修ing(研一版 || day40)
java·开发语言·学习·算法
zzzsde19 小时前
【数据结构】队列
数据结构·算法
青 .20 小时前
数据结构---二叉搜索树的实现
c语言·网络·数据结构·算法·链表
Zz_waiting.20 小时前
Javaweb - 14.6 - Vue3 数据交互 Axios
开发语言·前端·javascript·vue·axios
萌新小码农‍20 小时前
Java分页 Element—UI
java·开发语言·ui
Tiger_shl20 小时前
【.Net技术栈梳理】03-核心框架与运行时(异常处理)
开发语言·.net
再睡亿分钟!20 小时前
Spring MVC 的常用注解
java·开发语言·spring boot·spring
MChine慕青20 小时前
顺序表与单链表:核心原理与实战应用
linux·c语言·开发语言·数据结构·c++·算法·链表
qq_1955516920 小时前
代码随想录70期day7
java·开发语言