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

相关推荐
李绍熹21 分钟前
c语言字符串操作示例
c语言
徐先生 @_@|||23 分钟前
(Wheel 格式) Python 的标准分发格式的生成规则规范
开发语言·python
利剑 -~27 分钟前
jdk源码解析
java·开发语言
Damon_X30 分钟前
extern “C“
c语言
Predestination王瀞潞32 分钟前
JDK安装及环境变量配置
java·linux·开发语言
lsx20240638 分钟前
Python break 语句详解
开发语言
hmbbcsm38 分钟前
python做题小记(八)
开发语言·c++·算法
wyzqhhhh1 小时前
京东啊啊啊啊啊
开发语言·前端·javascript
JIngJaneIL1 小时前
基于java+ vue助农电商系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
雷中听风1 小时前
使用字节的源安装rust
开发语言·后端·rust