ESP-IDF:链表例程实现创建,增加,打印数据成员,释放链表空间等功能
创始人
2024-05-11 23:30:06
0

链表例程:

typedef struct LISTNODE
{
void *data_p;
LISTNODE *next;
} mlistnode;

typedef struct MYLIST
{
int size;
mlistnode *head;
} mylist;

mylist *initial_mylist()
{
mylist *p = (mylist *)malloc(sizeof(mylist));
p->size = 0;
p->head = (mlistnode *)malloc(sizeof(mlistnode));
p->head->data_p = NULL;
p->head->next = NULL;
return p;
}

void freemylist(mylist *plist)
{
if (plist == NULL)
{
return;
}
mlistnode *pCurrent = plist->head; // 创建一个节点指针指向当前要删除的节点,这里是要删除head节点
mlistnode *pNext = NULL;
while (pCurrent != NULL)
{
// mlistnode *pNext = pCurrent->next; // 再创建一个节点指针指向下一个要删除的节点
pNext = pCurrent->next;
free(pCurrent); // 删除当前节点
pCurrent = pNext; // 指向下一个要删除的节点
}
free(plist);
}
// 插入数据
void insertData(mylist *plist, void *pdata, int pos)
{
if (plist == NULL)
{
return;
}
if (pos < 0 && pos > plist->size)
{
return;
}

mlistnode *newNode = (mlistnode *)malloc(sizeof(mlistnode));
newNode->data_p = pdata;
newNode->next = NULL;mlistnode *pCurrent = plist->head;
for (int i = 0; i < pos; i++)
{pCurrent = pCurrent->next;
}newNode->next = pCurrent->next;
pCurrent->next = newNode;plist->size++;

}

// 打印链表
struct personlist
{
string name;
int age;
};

typedef void (*MYPRINT)(void *);
void myprint(void *datap)
{
personlist *p = (personlist *)datap;
cout << “名字是:” << p->name << " 年龄是:" << p->age << endl
<< endl;
};

void printmylist(mylist *listp, MYPRINT mprint)
{
if (listp == NULL)
{
return;
}
mlistnode *pCurrent = listp->head->next;
for (int i = 0; i < listp->size; i++)
{
mprint(pCurrent->data_p);
pCurrent = pCurrent->next;
}
}

void test08()
{
personlist p1 = {“AAA”, 21};
personlist p2 = {“BBB”, 22};
personlist p3 = {“CCC”, 23};
personlist p4 = {“DDD”, 24};
personlist p5 = {“EEE”, 25};

mylist *mlist = initial_mylist();
insertData(mlist, &p1, 0);
insertData(mlist, &p2, 0);
insertData(mlist, &p3, 0);
insertData(mlist, &p4, 0);
insertData(mlist, &p5, 0);
printmylist(mlist, myprint);

}

extern “C” void app_main(void)
{
test08();
}

结果:

在这里插入图片描述

相关内容

热门资讯

监控摄像头接入GB28181平... 流程简介将监控摄像头的视频在网站和APP中直播,要解决的几个问题是:1&...
Windows10添加群晖磁盘... 在使用群晖NAS时,我们需要通过本地映射的方式把NAS映射成本地的一块磁盘使用。 通过...
protocol buffer... 目录 目录 什么是protocol buffer 1.protobuf 1.1安装  1.2使用...
在Word、WPS中插入AxM... 引言 我最近需要写一些文章,在排版时发现AxMath插入的公式竟然会导致行间距异常&#...
【PdgCntEditor】解... 一、问题背景 大部分的图书对应的PDF,目录中的页码并非PDF中直接索引的页码...
Fluent中创建监测点 1 概述某些仿真问题,需要创建监测点,用于获取空间定点的数据࿰...
educoder数据结构与算法...                                                   ...
MySQL下载和安装(Wind... 前言:刚换了一台电脑,里面所有东西都需要重新配置,习惯了所...
修复 爱普生 EPSON L4... L4151 L4153 L4156 L4158 L4163 L4165 L4166 L4168 L4...
MFC文件操作  MFC提供了一个文件操作的基类CFile,这个类提供了一个没有缓存的二进制格式的磁盘...