在链表的使用时,结构对象所包含的数据各不相同,所以在链表的存储需要针对不同的链表对象重复编写相应的存储方法,能不能实现一种通用的方式,能够针对不同的结构对象,实现统一的存储方法?当然能。
一般我们在存储链表时,都会存储链表对象结构的首地址,也就是结构指针。在计算机中,对于指针,在32位机器上,实际就是四个字节的存储单元,里面存储了结构的首地址。可以利用这一点,在对象结构的首元素上做文章。
首先,定义一个对象,对象包含next指针和prev指针:
typedef struct list_head
{
struct list_head *next, *prev;
} LIST_HEAD_ST;
- 链表初始化
/* init list */
#define INIT_LIST_HEAD(name)\
{\
&(name), &(name)\
}
2.插入元素
static void list_add(struct list_head * const pstrunew,
struct list_head *prev,
struct list_head *next)
{
next->prev = pstrunew;
pstrunew->next = next;
pstrunew->prev = prev;
prev->next = pstrunew;
}
/* add after head */
static void list_add_head(struct list_head * const pstrunew, struct list_head *head)
{
list_add(pstrunew, head, head->next);
}
/* add before head */
static void list_add_tail(struct list_head * const pstrunew, struct list_head *head)
{
list_add(pstrunew, head->prev, head);
}
在定义对象结构时,将结构的首元素定义为
struct list_head *next, *prev
:
typedef struct test
{
struct list_head *next, *prev;
char chName[20];
...
} TEST_ST;