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。

相关推荐
qing_0406031 分钟前
C++——string的了解和使用
开发语言·c++·string
sjsjs111 分钟前
【数据结构-扫描线】力扣57. 插入区间
数据结构·算法·leetcode
xiaozhang_749338012 分钟前
数据结构day2
数据结构
王哈哈嘻嘻噜噜3 分钟前
数据结构中线性表的定义和特点
数据结构·算法
The Straggling Crow18 分钟前
go 战略
开发语言·后端·golang
MogulNemenis23 分钟前
力扣415周赛
java·数据结构·算法·leetcode
ai安歌25 分钟前
【JavaWeb】利用IDEA2024+tomcat10配置web6.0版本搭建JavaWeb开发项目
java·开发语言·后端·tomcat·web·intellij idea
尘浮生37 分钟前
Java项目实战II基于Java+Spring Boot+MySQL的作业管理系统设计与实现(源码+数据库+文档)
java·开发语言·数据库·spring boot·后端·mysql·spring
Alphapeople1 小时前
Qt中的延时
开发语言·qt
奇点 ♡1 小时前
【线程】线程的控制
linux·运维·c语言·开发语言·c++·visual studio code