【C语言实现内核链表】

以下是一个使用 C 语言实现简单内核链表的示例代码:

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

// 定义链表节点结构体
typedef struct ListNode {
    int data;
    struct ListNode *next;
} ListNode;

// 创建新节点
ListNode* createNode(int data) {
    ListNode* newNode = (ListNode*)malloc(sizeof(ListNode));
    if (newNode == NULL) {
        printf("内存分配失败\n");
        return NULL;
    }
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

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

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

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

int main() {
    ListNode* head = NULL;

    insertAtHead(&head, 10);
    insertAtHead(&head, 20);
    insertAtHead(&head, 30);

    printf("链表: ");
    printList(head);

    freeList(head);

    return 0;
}

在上述代码中,我们定义了链表节点结构体 ListNode,实现了创建节点、插入节点到头部、打印链表和释放链表内存的函数。在 main 函数中进行了简单的测试。

相关推荐
從南走到北几秒前
JAVA代泊车接机送机服务代客泊车系统源码支持小程序+APP+H5
java·开发语言·微信小程序·小程序
earthzhang20213 小时前
【1028】字符菱形
c语言·开发语言·数据结构·c++·算法·青少年编程
hjlgs3 小时前
Linux中双向链表介绍
数据结构·链表
earthzhang20215 小时前
第3讲:Go垃圾回收机制与性能优化
开发语言·jvm·数据结构·后端·性能优化·golang
纵有疾風起6 小时前
C++——类和对象(3)
开发语言·c++·经验分享·开源
Full Stack Developme6 小时前
java.text 包详解
java·开发语言·python
文火冰糖的硅基工坊6 小时前
[嵌入式系统-135]:主流AIOT智能体开发板
开发语言·嵌入式·cpu
承渊政道7 小时前
动态内存管理
c语言·c++·经验分享·c#·visual studio
yudiandian20147 小时前
02 Oracle JDK 下载及配置(解压缩版)
java·开发语言
要加油哦~7 小时前
JS | 知识点总结 - 原型链
开发语言·javascript·原型模式