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

相关推荐
slandarer34 分钟前
MATLAB | 绘图复刻(十九)| 轻松拿捏 Nature Communications 绘图
开发语言·matlab
狐凄35 分钟前
Python实例题:Python计算二元二次方程组
开发语言·python
roman_日积跬步-终至千里1 小时前
【Go语言基础【3】】变量、常量、值类型与引用类型
开发语言·算法·golang
roman_日积跬步-终至千里1 小时前
【Go语言基础】基本语法
开发语言·golang·xcode
Felven1 小时前
C. Basketball Exercise
c语言·开发语言
可乐鸡翅好好吃1 小时前
通过BUG(prvIdleTask、pxTasksWaitingTerminatio不断跳转问题)了解空闲函数(prvIdleTask)和TCB
c语言·stm32·单片机·嵌入式硬件·bug·keil
海棠蚀omo2 小时前
C++笔记-C++11(一)
开发语言·c++·笔记
Y第五个季节2 小时前
docker-部署Nginx以及Tomcat
java·开发语言
小道士写程序2 小时前
Qt 5.12 上读取 .xlsx 文件(Windows 平台)
开发语言·windows·qt