不太理解这段代码中treeLink()函数的操作,请大神们指点,那个*hook到底起了什么作用?
/* link operations for top-down splay */
/* this pastes a node in as !d-most node in subtree on side d */
static inline void
treeLink(struct tree ***hook, int d, struct tree *node)
{
*hook[d] = node;
/* strictly speaking we don't need to do this, but it allows printing the partial trees */
node->child[!d] = 0;
hook[d] = &node->child[!d];
}
/* splay last element on path to target to root */
static void
treeSplay(struct tree **root, int target)
{
struct tree *t;
struct tree *child;
struct tree *grandchild;
struct tree *top[TREE_NUM_CHILDREN]; /* accumulator trees that will become subtrees of new root */
struct tree **hook[TREE_NUM_CHILDREN]; /* where to link new elements into accumulator trees */
int d;
int dChild; /* direction of child */
int dGrandchild; /* direction of grandchild */
/* we don't need to keep following this pointer, we'll just fix it at the end */
t = *root;
/* don't do anything to an empty tree */
if(t == 0) { return; }
/* ok, tree is not empty, start chopping it up */
for(d = 0; d < TREE_NUM_CHILDREN; d++) {
top[d] = 0;
hook[d] = &top[d];
}
/* keep going until we hit the key or we would hit a null pointer in the child */
while(t->key != target && (child = t->child[dChild = t->key < target]) != 0) {
/* child is not null */
grandchild = child->child[dGrandchild = child->key < target];
treePrint(top[0]);
puts("---");
treePrint(t);
puts("---");
treePrint(top[1]);
puts("===");
if(grandchild == 0 || child->key == target) {
/* zig case; paste root into opposite-side hook */
treeLink(hook, !dChild, t);
t = child;
/* we can break because we know we will hit child == 0 next */
break;
} else if(dChild == dGrandchild) {
/* zig-zig case */
/* rotate and then hook up child */
/* grandChild becomes new root */
treeRotate(&t, dChild);
treeLink(hook, !dChild, child);
t = grandchild;
} else {
/* zig-zag case */
/* root goes to !dChild, child goes to dChild, grandchild goes to root */
treeLink(hook, !dChild, t);
treeLink(hook, dChild, child);
t = grandchild;
}
}
/* now reassemble the tree */
/* t's children go in hooks, top nodes become t's new children */
for(d = 0; d < TREE_NUM_CHILDREN; d++) {
*hook[d] = t->child[d];
t->child[d] = top[d];
}
/* and put t back in *root */
*root = t;
}
你node的定义中左右孩子应该是放在了某个数组中,hood其实还是指向了某个节点。
好好看下zig, zig-zig, zig-zag这三种的本质。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。