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。

相关推荐
程子的小段3 小时前
C 语言实例 - 字符串复制
c语言·开发语言
對玛祷至昏3 小时前
数据结构理论知识
数据结构·算法·排序算法
黄思搏3 小时前
红黑树 - Red-Black Tree 原理与 C# 实现
数据结构·1024程序员节
-森屿安年-3 小时前
STL 容器:stack
开发语言·c++
歪歪1003 小时前
C#如何在数据可视化工具中进行数据筛选?
开发语言·前端·信息可视化·前端框架·c#·visual studio
剑锋所指,所向披靡!3 小时前
数据结构的基本概念
数据结构
Jyywww1214 小时前
Python基于实战练习的知识点回顾
开发语言·python
Tony Bai4 小时前
【Go 网络编程全解】14 QUIC 与 HTTP/3:探索下一代互联网协议
开发语言·网络·后端·http·golang
爱吃小胖橘4 小时前
高效对象池设计:提升Unity性能的关键
开发语言·unity·c#·游戏引擎
dragoooon344 小时前
[优选算法专题四.前缀和——NO.31~32 连续数组、矩阵区域和]
数据结构·算法·leetcode·1024程序员节