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。

相关推荐
鸽鸽程序猿几秒前
【项目】【抽奖系统】注册功能实现
java·开发语言
QuantumLeap丶34 分钟前
【数据结构:从0-1】-01-数据结构介绍及学习路线规划
数据结构
云泽80838 分钟前
C/C++内存管理详解:从基础原理到自定义内存池原理
java·c语言·c++
weixin_3077791341 分钟前
在Linux服务器上使用Jenkins和Poetry实现Python项目自动化
linux·开发语言·python·自动化·jenkins
润 下41 分钟前
C语言——深入解析C语言指针:从基础到实践从入门到精通(四)
c语言·开发语言·人工智能·经验分享·笔记·程序人生·其他
Empty_7771 小时前
Python编程之常用模块
开发语言·网络·python
Code小翊1 小时前
堆的基础操作,C语言示例
java·数据结构·算法
小火柴1231 小时前
利用R绘制箱线图
开发语言·r语言
Emilia486.1 小时前
【Leetcode&nowcode&数据结构】顺序表的应用
数据结构·算法·leetcode
wheeldown1 小时前
【Linux】Linux 进程通信:System V 共享内存(最快方案)C++ 封装实战 + 通信案例,4 类经典 Bug 快速修复
linux·运维·服务器·开发语言