前言
- 近期在学习STM32代码框架的过程中,老师使用链表来注册设备,发现使用了不带头节点的单链表,注册时使用头插法。
- 之前在本专题整理学习过带头节点的单链表,因此本文整理对比一下两种方式的头插法区别,具体实现在次,重点在于用以理解两种思路,以及链表在嵌入式编码中的典型应用。
1.带头节点的链表
typedef struct Node
{
int data;
struct Node* next;
}Node;
Node* initList()
{
Node* list=(Node*)malloc(sizeof(Node));
list->data=0;
list->next=NULL;
return list;
}
void headINSERT(Node* list,int data)
{
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->next = list->next;
list->next = node;
list->data++;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
2.带头节点的链表
static InputDevice g_tKeyDevice = {
"gpio_key",
NULL,
GPIOKeyInit,
NULL,
};
void AddInputDeviceGPIOKey(void)
{
InputDeviceRegister(&g_tKeyDevice);
}
void InputDeviceRegister(PInputDevice ptInputDevice)
{
ptInputDevice->pNext = g_ptInputDevices;
g_ptInputDevices = ptInputDevice;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
3.对比总结
- 通过上述代码可看出,第二种方式少了头节点。
- 在使用链表时,第一种方式初始化需要对头节点内容进行初始赋值,包括data域数量为0和next域值指向为空。
- 而第二种方式初始化时不需要赋值,即头节点指针直接为空,需要用时直接注册插入即可,省去了头节点,代码上更加高效便捷。
- 一般而言头节点没有存在的必要时(遍历找最后一个Null也可以实现)完全可以使用第二种方式来实现链表注册。
- 同时,注册设备这也是链表在嵌入式实战中的一个典型应用,需要牢记。