【问题标题】:Inserting node into BST changes previous nodes将节点插入 BST 会更改以前的节点
【发布时间】:2021-11-12 13:33:41
【问题描述】:

我是 BST 概念的新手,为了完成作业,我必须使用该概念制作填字游戏。除了尝试将新单词插入 BST 之外,其他一切工作正常。 例如,如果: 词一:剑 单词 2: TWIRL

节点 1 和 2 都将在其字值中保存 TWIRL。

下面 sn-p 中的输入部分已简化,但知道root = insertWord(root, count, column, row, oriId, word); 存储在 do-while 循环的末尾可能很有用,尽管这不会影响事情。

结构声明

struct Words {
    int id;
    int col;
    int row;
    int ori; // 0 Horizontal, 1 Vertical
    char *word;
    Words *left, *right;
} *root = NULL;

BST 插入

Words *newWord(int id, int col, int row, int ori, char *word) {
    Words *newWord = (Words*)malloc(sizeof(Words));
    newWord->id = id;
    newWord->col = col;
    newWord->row = row;
    newWord->ori = ori;
    newWord->word = word;
    newWord->left = NULL;
    newWord->right = NULL;
    
    return newWord;
}

Words *insertWord(Words *node, int id, int col, int row, int ori, char *word) {
    if(node == NULL) {
        node = newWord(id, col, row, ori, word);
    }
    else if(id > node->id) {
        node->right = insertWord(node->right, id, col, row, ori, word);
    }
    else if(id < node->id) {
        node->left = insertWord(node->left, id, col, row, ori, word);
    }
    else {
        printf("Can't insert the same value");
    }
    
    return node;
}

输入

char word[25];
print("Word [1 to go back] : "); scanf(" %s", &word);
root = insertWord(root, count, column, row, oriId, word);
// count is the number of words, oriId is orientation

提前谢谢你

【问题讨论】:

  • 您不是在制作数据的副本,而是保存一个指向缓冲区的指针。因此,下一个数据条目将更改所有先前的条目,因为它们都指向同一个缓冲区。考虑使用newWord-&gt;word = strdup(word);。另外:scanf(" %s", &amp;word); 应该是 scanf("%24s", word);
  • 例如newWord-&gt;word = word; 想想那是做什么的。实际上,在调试器中运行您的程序并在该行设置断点,然后单步执行并查看每次执行时实际发生的情况,密切注意所存储地址的值,不是里面的字符串内容。
  • 我想我现在明白了,我昨天用 BST 制作了另一个程序(一个更简单的程序)并且 node->char* = char* 在那里工作得很好,所以我认为这就是这样做的方法。读入 strdup 虽然我明白为什么这是正确的做法。谢谢你们提供的信息,我还有很多关于 C 和 BST 的知识。
  • Words *left, *right;
  • 是的,我使用的是 cpp 文件类型

标签: c binary-search-tree


【解决方案1】:

首先,您不会在插入过程中遍历您的列表。然后你可以通过这种方式缩短你的代码。

struct Word **trav = node; // double pointer holds address        of root

while(*trav != null){
    if( id < *trav->id){
        trav = *trav->left;
    }else{
        trav = *trav->right;
    }
 }

 new_data = new Word(…);
 *trav = &new_data;

(对不起,我在手机上编码太难了)

【讨论】:

    猜你喜欢
    • 2017-06-14
    • 1970-01-01
    • 2019-09-06
    • 2012-10-14
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    相关资源
    最近更新 更多