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

相关推荐
Villiam_AY31 分钟前
Redis 缓存机制详解:原理、问题与最佳实践
开发语言·redis·后端
UQWRJ1 小时前
菜鸟教程R语言一二章阅读笔记
开发语言·笔记·r语言
岁忧2 小时前
macOS配置 GO语言环境
开发语言·macos·golang
朝朝又沐沐4 小时前
算法竞赛阶段二-数据结构(36)数据结构双向链表模拟实现
开发语言·数据结构·c++·算法·链表
魔尔助理顾问4 小时前
系统整理Python的循环语句和常用方法
开发语言·后端·python
Ares-Wang4 小时前
JavaScript》》JS》 Var、Let、Const 大总结
开发语言·前端·javascript
遇见尚硅谷5 小时前
C语言:*p++与p++有何区别
c语言·开发语言·笔记·学习·算法
SkyrimCitadelValinor5 小时前
c#中让图片显示清晰
开发语言·c#
艾莉丝努力练剑5 小时前
【数据结构与算法】数据结构初阶:详解排序(二)——交换排序中的快速排序
c语言·开发语言·数据结构·学习·算法·链表·排序算法
狐小粟同学5 小时前
JavaEE--3.多线程
java·开发语言·java-ee