??在学习数据结构时发现函数中修改指针参数的值无效,学习之后发现,把指针作为一个参数传递给函数时,是将指针的副本传递给了函数,所以在函数中修改指针参数只是修改了指针的copy而不是指针本身,解决方法: 1.指针的引用
struct BitTree
{
BitNode<ElemType> *root = nullptr;
}
struct BitNode{
ElemType data;
struct BitNode<ElemType> *lchild = nullptr,*rchild = nullptr; // 左右孩子指针
BitNode(){}
BitNode(ElemType e): data(e) {}
};
int BST_insert(BitNode<int>*& node, int e) // 二叉排序树的插入
{
if(!node)
{
node = new BitNode<int>(e);
BitNode<int> n = (*node);
cout<<"*node:"<<n.data<<endl;
return 1;
}else if(e == node->data)
return 0; // 存在相同关键值的节点,插入失败
else if(e > node->data)
return BST_insert(node->rchild, e);
else
return BST_insert(node->lchild, e);
}
//实现
void testBST()
{
srand(time(0));
BitTree<int> bt1;
for(int i = 10; i > 0;i--)
{
int randnum = rand() % 100;
BST_insert(bt1.root, randnum);
}
inOrder(bt1.root);
}
BST_insert(BitNode*& node, int e) node: 指针的引用,即testBst里的bt1.root的引用,类型:BitNode* *node: 即testBst里bt1.root指针指向的BitNode类,类型:BitNode
输出:最后一行为二叉排序树的中序遍历输出
2.指针的指针
int BST_insert(BitNode<int>** node, int e) // 二叉排序树的插入
{
if(!(*node))
{
*node = new BitNode<int>(e);
return 1;
}else if(e == (*node)->data)
return 0; // 存在相同关键值的节点,插入失败
else if(e > (*node)->data)
return BST_insert(&(*node)->rchild, e);
else
return BST_insert(&(*node)->lchild, e);
}
void testBST()
{
srand(time(0));
BitTree<int> bt1;
for(int i = 10; i > 0;i--)
{
int randnum = rand() % 100;
BST_insert(&bt1.root, randnum);
}
inOrder(bt1.root);
}
BST_insert(BitNode** node, int e)方法中 node: 指针的指针,存储指向指针的指针地址,一般不做修改,类型为BitNode** *node: 被指向的指针,修改它可以修改被指向的指针的内容,即testBST方法里的bt.root,类型为BitNode* **node: 两次解引用是指向testBST方法里的bt1.root指向的类对象,类型为BitNode
在testBST中: &bt1.root即获取bt.root的地址,类型为BitNode**
参考文章 https://www.cnblogs.com/li-peng/p/4116349.html
|