【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 函数中进行了简单的测试。

相关推荐
aaaameliaaa12 小时前
字符函数和字符串函数
c语言·笔记·算法
夜月yeyue12 小时前
AUTOSAR CP 从上电到 Runnable
c语言·网络·tcp/ip·车载系统
微学AI12 小时前
一根针指向所有方向:挂谷猜想对 LLM Agent 技能-记忆架构的启示
开发语言·人工智能·架构·挂谷猜想
豆瓣鸡13 小时前
算法日记 - Day3
java·开发语言·算法
白白白小纯13 小时前
算法篇—反转链表
c语言·数据结构·算法·leetcode
韭菜炒鸡肝天14 小时前
VTK开发笔记(一):VTK介绍,Qt..+VSx+VTK.编译
开发语言·笔记·qt
小羊先生car14 小时前
RTOS-F429-HAL-绝对延时和相对延时(2026/7/31)
c语言·rtos
Aaron - Wistron14 小时前
Web API C# (Furion版)带 单元测试
开发语言·后端·c#
Dxy123931021615 小时前
Python项目打包成EXE完整教程(PyInstaller实战避坑)
开发语言·python
05664616 小时前
Python康复训练——常用标准库
开发语言·python·学习