c - 运行函数时可执行文件崩溃
问题描述
我正在为分配创建一个 AVL,但是当我调用右旋转和左旋转函数时,可执行文件崩溃而没有错误消息。我认为这可能是由于 NULL 指针异常,但我不确定。
这是我的旋转代码:
TNODE *rotate_right(TNODE *y){
TNODE *x=y->left;
TNODE *t2=x->right;
x->right=y;
y->left=t2;
y->height =max(height(y->left),height(y->right))+1;
x->height=max(height(x->left),height(x->right))+1;
}
TNODE *rotate_left(TNODE *x){
TNODE *y=x->right;
TNODE *t2=y->left;
y->left=x;
x->right=t2;
y->height =max(height(y->left),height(y->right))+1;
x->height=max(height(x->left),height(x->right))+1;
}
这是我调用它们的插入函数:
void insert(TNODE **rootp, char *name, float score){
TNODE *np = (TNODE *) malloc(sizeof(TNODE));
if (np == NULL) return;
strcpy(np->data.name, name);
np->data.score = score;
np->height = 1;
np->left = NULL;
np->right = NULL;
// 1. Perform the normal BST insertion
if (*rootp == NULL) {
*rootp = np;
return;
}
TNODE *root = *rootp;
if (strcmp(name, root->data.name) < 0 ){
insert(&root->left, name, score);
}
else if (strcmp(name, root->data.name) > 0 ){
insert(&root->right, name, score);
}
else return ;
// 2. update height of this root node
// add your code here
root->height=height(root);
// STEP 3: get the balance factor of this root node
// add your code here
int balance=balance_factor(root);
// STEP 4: re-balance if not balanced
// add your code here
if(balance>1&&balance_factor(root->left)>=0){
rotate_right(root);
}
else if(balance>1&&balance_factor(root->left)<0){
rotate_left(root->left);
rotate_right(root);
}
else if(balance<-1&&balance_factor(root->right)>=0){
rotate_left(root);
}
else if(balance<-1&&balance_factor(root->right)<0){
rotate_right(root->right);
rotate_left(root);
}
}
如果我注释掉我必须旋转它的最后一部分,代码运行良好,所以我很确定问题就在那里。提前感谢您的帮助。
解决方案
推荐阅读
- python - 如何快速将切片从 cuda 张量 wrt 切割成另一个张量值
- c++ - OpenGL:透视分割是如何工作的?
- python - 如何在 python 中将 YAML 拆分为不同的文件?
- linux-kernel - 在本机 ARM 设备上编译 Linux 内核后,加载模块失败
- powershell - 查找数组是否有值,然后从该数组中复制 id
- python - Python 字符串切片教程
- c# - 在 SSIS 中不使用公共数据源创建数据表
- java - Zip 2 different Mono in Spring Webfux
- wordpress - 如果 Woocommerce 中没有折扣隐藏表格行
- python - Anaconda-installation:需要 MX-Linux 的软件包