PDF版 ePub版

# 数组(C中的)与链表

### 数组

int a[3];
a[0]=1;
a[2]=3;

zval ***args = safe_emalloc(ZEND_NUM_ARGS(), sizeof(zval**), 0);

### 链表

typedef struct _namelist namelist;
struct _namelist
{
struct _namelist *next;
char *name;
};

static namelist *people;

//通过一个循环来遍历这个链表中的所有人～
void name_show(namelist *p)
{
while (p)
{
printf("Name: %s\n", p->name);
p = p->next;
}
}

static namelist *people = NULL, *last_person = NULL;
{
person->next = NULL;
if (!last_person) {
/* No one in the list yet */
people = last_person = person;
return;
}
/* Append new person to the end of the list */
last_person->next = person;

/* Update the list tail */
last_person = person;
}
namelist *name_pop(void)
{
namelist *first_person = people;
if (people) {
people = people->next;
}
return first_person;
}

typedef struct _namelist namelist;
struct
{
namelist *next, *prev;
char *name;
} _namelist;

{
person->next = NULL;
if (!last_person)
{
/* No one in the list yet */
people = last_person = person;
person->prev = NULL;
return;
}
/* Append new person to the end of the list */
last_person ->next = person;
person->prev = last_person;

/* Update the list tail */
last_person = person;
}

void name_remove(namelist *person)
{
namelist *p;
if (person == people) {
/* Happens to be the first person in the list */
people = person->next;
if (last_person == person) {
/* Also happens to be the last person */
last_person = NULL;
}
return;
}
/* Search for prior person */
p = people;
while (p) {
if (p->next == person) {
p->next = person->next;
if (last_person == person) {
/* This was the last element */
last_person = p;
}
return;
}
p = p->next;
}
}

void name_remove(namelist *person)
{
if (people == person) {
people = person->next;
}
if (last_person == person) {
last_person = person->prev;
}
if (person->prev) {

person->prev->next = person->next;
}
if (person->next) {
person->next->prev = person->prev;
}
}

### 王者归来：HashTable才是我们的银蛋！

HashTable既具有双向链表的优点，同时具有能与数据匹敌的操作性能，这个数据结构几乎是PHP内核实现的基础，我们在内核代码的任何地方都发现它的痕迹。

Zend Engine中HashTable的元素其实是指针，对其的这个改进使得HashTable能够包容各种类型的数据，从小小的标量，到复杂的PHP5中实现的类等复合数据。本章接下来的内容，我们将详细的研究如何使用zend内置的API来操作HashTable这个数据结构。