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

相关推荐
翔云API2 分钟前
人证合一接口:智能化身份认证的最佳选择
大数据·开发语言·node.js·ocr·php
jimmy.hua3 分钟前
C++刷怪笼(5)内存管理
开发语言·数据结构·c++
xiaobai12 36 分钟前
二叉树的遍历【C++】
开发语言·c++·算法
DieSnowK13 分钟前
[项目][WebServer][Makefile & Shell]详细讲解
开发语言·c++·http·makefile·shell·项目·webserver
Freak嵌入式13 分钟前
全网最适合入门的面向对象编程教程:50 Python函数方法与接口-接口和抽象基类
java·开发语言·数据结构·python·接口·抽象基类
冷凝女子16 分钟前
【QT】基于HTTP协议的网络应用程序
开发语言·qt·http
知识分享小能手19 分钟前
mysql学习教程,从入门到精通,SQL 删除数据(DELETE 语句)(19)
大数据·开发语言·数据库·sql·学习·mysql·数据开发
鸽芷咕28 分钟前
【Python报错已解决】libpng warning: iccp: known incorrect sRGB profile
开发语言·python·机器学习·bug
白总Server34 分钟前
MongoDB解说
开发语言·数据库·后端·mongodb·golang·rust·php
XyLin.36 分钟前
Msf之Python分离免杀
开发语言·python·网络安全·系统安全