不使用malloc的链表
创始人
2024-12-29 01:30:32
0

创建一个不使用malloc的链表可以使用静态数组来存储节点。以下是一个示例代码:

#include 

#define MAX_SIZE 100

typedef struct Node {
    int data;
    int next;
} Node;

void initList(Node list[], int size) {
    int i;
    for (i = 0; i < size - 1; i++) {
        list[i].next = i + 1;
    }
    list[size - 1].next = -1; // 表示链表结束
}

int main() {
    Node list[MAX_SIZE];
    initList(list, MAX_SIZE);

    // 在链表末尾添加两个节点
    int newNodeIndex = list[0].next;
    list[newNodeIndex].data = 100;
    list[newNodeIndex].next = list[newNodeIndex + 1].next;
    list[newNodeIndex + 1].data = 200;
    list[newNodeIndex + 1].next = -1;

    // 输出链表节点数据
    int currentIndex = list[0].next;
    while (currentIndex != -1) {
        printf("%d ", list[currentIndex].data);
        currentIndex = list[currentIndex].next;
    }
    printf("\n");

    return 0;
}

在这个示例代码中,我们通过定义一个静态数组 list 来存储链表节点。initList 函数用于初始化链表,其中 size 参数表示数组的大小。通过遍历数组,将每个节点的 next 字段设置为下一个节点的索引值。最后一个节点的 next 字段设置为 -1,表示链表结束。

main 函数中,我们使用 initList 函数初始化链表。然后,我们通过访问数组来添加新的节点。在这个示例中,我们在链表末尾添加了两个节点,并设置了节点的数据和下一个节点的索引。最后,我们遍历链表并输出节点的数据。

请注意,由于使用静态数组,链表的大小是固定的,不能动态地添加或删除节点。如果需要动态地操作链表,您可能需要考虑使用其他方法,如使用指针和动态内存分配。

相关内容

热门资讯

透视计算!hh poker插件... 透视计算!hh poker插件下载,hh poker辅助有用吗,揭秘攻略(有挂解密)1、hh pok...
透视辅助!hhpoker有后台... 透视辅助!hhpoker有后台操作吗,hhpoker德州机器人,科技教程(有挂教程)1、许多玩家不知...
透视计算!hhpoker视频巡... 透视计算!hhpoker视频巡查真的假的,hhpoker有后台操作吗,切实教程(有挂方法)小薇(透视...
透视挂透视!hhpoker脚本... 透视挂透视!hhpoker脚本下载,hhpoker脚本下载,2025新版教程(有挂详情)1、玩家可以...
透视有挂!hhpoker作弊码... 透视有挂!hhpoker作弊码,hhpoker真的假的,可靠教程(有挂解说)1、许多玩家不知道hhp...
透视线上!hhpoker是内部... 透视线上!hhpoker是内部控制吗,德州透视hhpoker,必备教程(有挂技巧)1、透视线上!hh...
透视新版!hhpoker免费透... 透视新版!hhpoker免费透视脚本,hhpoker怎么防作弊,技巧教程(有挂揭秘);1、玩家可以在...
透视肯定!hhpoker软件安... 透视肯定!hhpoker软件安装包,hhpkoer辅助器,可靠技巧(有挂介绍)所有人都在同一条线上,...
透视ai!hhpoker怎么破... 透视ai!hhpoker怎么破解,hhpoker真能买到挂吗,德州论坛(有挂细节);1、每一步都需要...
透视科技!hhpoker辅助软... 透视科技!hhpoker辅助软件,hhpoker外挂靠谱吗,2025新版教程(有挂揭秘);1、进入到...