C语言 为什么我的 while 循环忽略 NULL 条件?



>我正在尝试做一个将值插入二叉树的函数。insertbin(...( 中的第一个 while 循环在移动到下一个元素后等于 NULL 时完全忽略 x 值。我的病情有问题吗?

我尝试使用 prev 节点来检查条件,但它仍然不起作用。

#include <stdlib.h>
#include <stdio.h>
#include "Queue_arr.h"
tree* createtree() {
tree*mytree = (tree*)malloc(sizeof(tree));
mytree->root = NULL;
return mytree;
}
void insertbin(tree* T, int data) {
treenode *x, *y, *z;
int flag = 1;
z = (treenode*)malloc(sizeof(treenode));
y = NULL;
x = T->root;
z->key = data;
while (x != NULL) //While the tree isn't empty
{
y = x;
if (z->key < x->key) //If the data is smaller than the existing key to the left
x = x->sonleft;
else //Else, to the right
x = x->sonright;
}
z->father = y;
if (y == NULL) //If y is the root
T->root = z;
else
if (z->key < y->key) //If the data is smaller than the existing key to the left
y->sonleft = z;
else //Else, to the right
y->sonright = z;
}
void insertscan(tree *T) //Scans the data to insert to the tree via insertbin(...)
{
int data;
printf("Enter a number (Enter a negative number to stop): n");
scanf("%d", &data);
while (data >= 0)
{
insertbin(T, data);
scanf("%d", &data);
}
}

void main()
{
tree* T;
T = createtree();
insertscan(T);
}

我将 z 定义中的malloc更改为calloc并解决了它。 一定是因为malloc没有用NULL填充你的价值观.

(感谢用户3365922(

相关内容

  • 没有找到相关文章

最新更新