现在的位置: 首页 > 综合 > 正文

【算法导论】指针作为形式参数时 改变指针所指的值(二叉排序树)

2013年10月06日 ⁄ 综合 ⁄ 共 1042字 ⁄ 字号 评论关闭

 例题一:让原本指向空的两个指针,赋值

#include"stdio.h"

#include"malloc.h"
#include"string.h"
void TestFunction(char** ptr1, char*& ptr2)//我经常喜欢用 *&ptr2
{
*ptr1 = "abc";
ptr2 = (char*)malloc(6);
strcpy(ptr2, "abc");
}

int main()
{
char* ptr1 = NULL, *ptr2 = NULL;
TestFunction(&ptr1, ptr2);
printf("%s\n", ptr1);
printf("%s\n", ptr2);
free(ptr2);
}

例题二:二叉排序树的实现
#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;
}

抱歉!评论已关闭.