指针作为形式参数时 改变指针所指的值(二叉排序树)

例题一:让原本指向空的两个指针,赋值
<wbr><span style="font-size:18px"><strong>#include"stdio.h"</strong></span> <div><span style="font-size:18px"><strong>#include"malloc.h"</strong></span></div> <div><span style="font-size:18px"><strong>#include"string.h"</strong></span></div> <div><span style="font-size:18px"><strong>void TestFunction(char** ptr1, char*&amp; ptr2)//我经常喜欢用 *&amp;ptr2</strong></span></div> <div><span style="font-size:18px"><strong>{</strong></span></div> <div><span style="font-size:18px"><strong>*ptr1 = "abc";</strong></span></div> <div><span style="font-size:18px"><strong>ptr2 = (char*)malloc(6);</strong></span></div> <div><span style="font-size:18px"><strong>strcpy(ptr2, "abc");</strong></span></div> <div><span style="font-size:18px"><strong>}</strong></span></div> <div><span style="font-size:18px"><br><strong></strong></span></div> <div><span style="font-size:18px"><strong>int main()</strong></span></div> <div><span style="font-size:18px"><strong>{</strong></span></div> <div><span style="font-size:18px"><strong>char* ptr1 = NULL, *ptr2 = NULL;</strong></span></div> <div><span style="font-size:18px"><strong>TestFunction(&amp;ptr1, ptr2);</strong></span></div> <div><span style="font-size:18px"><strong>printf("%s\n", ptr1);</strong></span></div> <div><span style="font-size:18px"><strong>printf("%s\n", ptr2);</strong></span></div> <div><span style="font-size:18px"><strong>free(ptr2);</strong></span></div> <div><span style="font-size:18px"><strong>}</strong></span></div> </wbr>
例题二:二叉排序树的实现
#include"stdio.h"
#include"malloc.h"
struct node
{
int data;
node *right;
node *left;
};
void insert(node *&root,node *&s)//传递的参数是关键
{
if(root==NULL)
{
root=s;

}
else
{
if(root->data<s->data)//要插入的数据 data大于节点 则插入右边
insert(root->right,s);
else
insert(root->left,s);
}
}

void creatTree(node *&root,int a[],int n)
{
int i;
node *s;
//root=(node*)malloc(sizeof(node));//不要在这里初始化 或者申请空间之后 root=NULL;
for(i=0;i<n;i++)
{
s=(node *)malloc(sizeof(node));
s->data=a[i];
s->right=NULL;
s->left=NULL;

insert(root,s);
}

}
void outPut(node *&root)
{
if(root==NULL)
return;
else
{
outPut(root->left);
printf("%5d",root->data);
outPut(root->right);
}
}
int main()
{
int a[]={15,2,4,6,7,13,9,3,17,18,20};
node *root;
root=(node*)malloc(sizeof(node));//(申请空间大小)
root=NULL;//这一句一定不能少 (初始化)
creatTree(root,a,11);
outPut(root);
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值