java - BST 从 Java 插入到 C

标签 java c insert binary-search-tree

我目前正在学习 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/

相关文章:

java - Jackson @JsonFormat 用不正确的时区转换日期

java - 如何从 Spring Controller 获取angularjs中的模型属性值

我可以将 const char* 数组传递给 execv 吗?

c# - C/C++ 和 C#/Java 之间 volatile 的用法有什么区别?

mysql - 结果在插入期间由多行组成

mysql - 插入查询在 mysql 中不起作用

java - 没有命名空间的 XML。针对多个 XSD 之一进行验证

java - 为什么 Point2D 的值有时表现为静态?

c - GCC 相关搜索目录

jquery - 无法在列表顶部插入第一个列表项,jQuery bug?