随笔 - 50  文章 - 8  trackbacks - 0
<2010年3月>
28123456
78910111213
14151617181920
21222324252627
28293031123
45678910

常用链接

留言簿

随笔档案

Blogs

搜索

  •  

最新评论

阅读排行榜

评论排行榜

5.4.2 Step 2: Insert

Following the search loop, q is the last non-null node examined, so it is the parent of the node to be inserted. The code below creates and initializes a new node as a child of q on side dir, and stores a pointer to it into n. Compare this code for insertion to that within <BST item insertion function 32>.

149. <Step 2: Insert AVL node 149> =
n = q->avl_link[dir] = 
  tree->avl_alloc->libavl_malloc (tree->avl_alloc, sizeof *n); if (n == NULL) return NULL; tree->avl_count++; n->avl_data = item; n->avl_link[0] = n->avl_link[1] = NULL; n->avl_balance = 0; if (y == NULL) return &n->avl_data;

This code is included in 146.

Exercises:

1. How can y be NULL? Why is this special-cased?
[answer]

Variable y is only modified within <Step 1: Search AVL tree for insertion point 148>. If y is set during the loop, it is set to p, which is always a non-null pointer within the loop. So y can only be NULL if it is last set before the loop begins. If that is true, it will be NULL only if tree->avl_root == NULL. So, variable y can only be NULL if the AVL tree was empty before the insertion.

A NULL value for y is a special case because later code assumes that y points to a node.

posted on 2010-10-05 01:42 sohu2000000 阅读(874) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航:   博客园   博客园最新博文   博问   管理