我有使用递归在二叉搜索树中插入值的 ds 代码。问题是根始终保持为空。
执行后,第一个 printf() 打印 10,但第二个 printf(在 insertRec(10) 之后)不会打印任何内容,因为 root 为 null。
#include<stdio.h>
#include<malloc.h>
struct llist
{
int data;
struct llist *left;
struct llist *right;
};
typedef struct llist node;
void insertRec(node *r, int num)
{
if(r==NULL)
{
r=(node*)malloc(sizeof(node));
r->data=num;
r->left=NULL;
r->right=NULL; printf("%d ",r->data); //1st printf
}
else
{
if(num < r->data)
insertRec(r->left, num);
else
insertRec(r->right, num);
}
}
void display(node *x)
{
if(x != NULL)
{
display(x->left);
printf("%d-->",x->data);
display(x->right);
}
else
return;
}
int main()
{
node *root=NULL;
insertRec(root,10);
if(root !=NULL)
printf("\ndata=%d",root->data); //2nd printf
insertRec(root,5);
insertRec(root,15);
insertRec(root,3);
insertRec(root,18);
display(root);
getch();
}
你正在路过root
作为价值所以改变root
在插入函数中不会反映在主函数中,因此root
在主函数中保持 NULL。要纠正您的代码,您需要传递指针到指针 https://stackoverflow.com/questions/18306935/need-of-pointer-to-pointer/18307020#18307020。传递地址root
以反映主要功能的变化。
void insertRec(node *r, int num)
应该编码如下:
void insertRec(node **r, int num)
{
if(*r==NULL)
{
*r= malloc(sizeof(node));
(*r)->data=num;
//
and use *root
内部插入功能。
并将其称为insertRec(&root, 10);
从主要。
此外,如果您动态分配内存,那么您应该显式使用 free 释放分配的内存。
又学到一件事缩进 C 程序 http://www.cs.arizona.edu/~mccann/indent_c.html.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)