background image
另外一种常见的存储数据的方式是链表
. 对于链表而言, 每个数据元素都是一个至少有
两个属性的结构体
: 一个指向链表中的下一个节点, 一个则是实际的数据. 考虑下面假设的
数据结构
:
typedef struct _namelist namelist;
struct {
struct namelist *next;
char *name;
} _namelist;
使用这个数据结构的引用需要定义一个变量
:
static namelist *people;
链表中的第一个名字可以通过检查
people 变量的 name 属性得到: people->name; 第
二个名字则访问
next 属性: people->next->name, 依此类推: people->next->next->name 等
, 直到 next 为 NULL 表示链表中已经没有其他名字了. 更常见的用法是使用循环迭代链
:
void name_show(namelist *p)
{
while (p) {
printf("Name: %s\n", p->name);
p = p->next;
}
}
这种链表非常适合于
FIFO 的链式结构, 新的数据被追加到链表的末尾, 从另外一端线
性的消耗数据
:
static namelist *people = NULL, *last_person = NULL;
void name_add(namelist *person)
{
person->next = NULL;
if (!last_person) {
/* 链表中没有数据 */
people = last_person = person;
return;