首先分配固定数量的子指针,然后添加一个成员来存储列表的当前容量. 当你go 添加一个子元素到列表,如果列表是一个容量,两倍大小. 这将减少您需要做的重新定位的数量.
所以一个 node 被修改为如下所示:
struct node {
int id;
int capacity;
int num_children;
struct node ** child;
};
要创建 node ,请执行以下操作:
struct node *newnode = malloc(sizeof *newnode);
newnode->num_children = 0;
newnode->capacity = 10;
newnode->child = malloc(sizeof *newnode->child * newnode->capacity);
要在能力时添加一个子元素:
if (current->capacity == current->num_children) {
current->capacity *= 2;
current->child = realloc(current->child,
sizeof *current->child * newnode->capacity);
}
current->child[current->num_children++] = new_child;
注意:为了简洁起见,省略了错误判断.