我正在尝试用C克隆AVLTree,但我有
BUS ERROR:10
在我的代码中。 我真的需要开始提高我的编程技能,很多。这就是为什么每隔一周,我一直在努力练习一些编程练习。对于这个,我决定做一个基本的AVL树。但我遇到这么多困难。
typedef struct AVLTreeNode {
int key;
int value;
int height;
struct AVLTreeNode *parent;
struct AVLTreeNode *left;
struct AVLTreeNode *right;
} AVLTreeNode;
typedef struct AVLTree{
int size; // count of items in avl tree
AVLTreeNode *root; // root
} AVLTree;
AVLTreeNode *newAVLTreeNode(int k, int v )
{
AVLTreeNode *new;
new = malloc(sizeof(AVLTreeNode));
assert(new != NULL);
new->key = k;
new->value = v;
new->height = 0; // height of this new node is set to 0
new->left = NULL; // this node has no child
new->right = NULL;
new->parent = NULL; // no parent
return new;
}
AVLTree *newAVLTree()
{
AVLTree *T;
T = malloc(sizeof (AVLTree));
assert (T != NULL);
T->size = 0;
T->root = NULL;
return T;
}
AVLTreeNode *CloneAVLTreeNode(AVLTreeNode *r)
{
AVLTreeNode *n;
if (r == NULL) return NULL;
else
{
n->key = r->key;
n->value = r->value;
n->height = r->height;
n->parent = r->parent;
n->left = CloneAVLTreeNode(r->left);
n->right = CloneAVLTreeNode(r->right);
return n;
}
}
AVLTree *CloneAVLTree(AVLTree *T)
{
AVLTree *New = malloc(sizeof(AVLTree));
//AVLTree *New;
AVLTreeNode *p = New->root;
AVLTreeNode *n = T->root;
if (n == NULL) return NULL;
else
{
p = CloneAVLTreeNode(n);
}
return New;
}
你们能给我一些提示,并指出我正确的方向。这真让我烦恼,因为我知道这个练习不应该这么困难。
提前致谢。
答案 0 :(得分:1)
至少有以下两个问题:
第一个问题:
AVLTreeNode *CloneAVLTreeNode(AVLTreeNode *r)
{
AVLTreeNode *n; // here you declare n, but n just points nowhere
if (r == NULL) return NULL;
else
{
n->key = r->key; // here n still points nowhere,
// therefore dereferencing it causes the Bus error.
n->value = r->value;
n->height = r->height;
n->parent = r->parent;
n->left = CloneAVLTreeNode(r->left);
n->right = CloneAVLTreeNode(r->right);
return n;
}
}
你可能想要这个:
AVLTreeNode *CloneAVLTreeNode(AVLTreeNode *r)
{
if (r == NULL) return NULL;
else
{
AVLTreeNode *n = malloc(sizeof AVLTreeNode); // allocate memory for new node
n->key = r->key;
n->value = r->value;
n->height = r->height;
n->parent = r->parent;
n->left = CloneAVLTreeNode(r->left);
n->right = CloneAVLTreeNode(r->right);
return n;
}
}
第二个问题:
AVLTree *CloneAVLTree(AVLTree *T)
{
AVLTree *New = malloc(sizeof(AVLTree));
//AVLTree *New;
AVLTreeNode *p = New->root; // here New->root hasn't been initialized either
// so p will point nowhere either
AVLTreeNode *n = T->root;
if (n == NULL) return NULL;
else
{
p = CloneAVLTreeNode(n); // but here you assign p with another value, so the previous 'p = New->root'
// is pointless anyway.
}
return New;
}
其他地方最有可能出现更多错误。