我目前正在学习 C 语言,并且在 Java 方面有很多经验。
我试图在 BST 上实现插入操作,我在 Java 中成功地完成了它,在 C 中的类似代码导致它失败,请有人帮我解决这个问题。
//Java代码(我用过泛型,其中Key是Comparable,另一个泛型是Value)
private class Node {
private Value value;
private Key key;
private Node left, right;
public Node(Key key, Value value) {
this.value = value;
this.key = key;
}
}
public void put(Key key, Value value) {
root = put(root, key, value);
}
public Node put(Node x, Key key, Value value) {
if (x == null)
return new Node(key, value);
int cmp = key.compareTo(x.key);
if (cmp < 0)
x.left = put(x.left, key, value);
else if (cmp > 0)
x.right = put(x.right, key, value);
else
x.value = value;
return x;
}
//C代码
struct Node {
int key;
int value;
struct Node *left, *right;
};
struct Node *root;
struct Node *put(struct Node *x, int key, int value) {
if (x == NULL) {
struct Node *newNode = malloc(sizeof(struct Node));
return newNode;
}
if (key < x->key)
x->left = insert(x->left,key,value);
else if (key > x->key)
x->right = insert(x->right,key,value);
else
x->value = value;
return x;
}
void putMain(int key, int value) {
root = insert(root, key, value);
}
最佳答案
好像你没有初始化newNode
struct Node *newNode = malloc(sizeof(struct Node));
newNode->key = key;
newNode->value = value;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
关于java - BST 从 Java 插入到 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20812087/