|
发表于 2007-4-27 11:44:12
|
显示全部楼层
Post by litao19
#include <stdio.h>
应该怎么改?
关键在于,C 中参数都是传值。如果你想在被调函数中修改调用函数中某变量的值,就要把该变量的地址传进去。参考下列代码
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct bnode
- {
- int data;
- struct bnode *left, *right;
- }btree;
- void creat(btree **b);
- void insert(btree **b, btree *s);
- void inorder(btree *b);
- int main()
- {
- btree *b;
- creat(&b);
- inorder(b);
- printf("\n");
- return 0;
- }
- void insert(btree **b, btree *s)
- {
- if(s == NULL) return;
- else if(*b == NULL) *b = s;
- else if((*b)->data == s->data) return;
- else if((*b)->data > s->data) insert(&(*b)->left, s);
- else if((*b)->data < s->data) insert(&(*b)->right, s);
- }
- void creat(btree **b)
- {
- int x;
- btree *s;
- *b=NULL;
- scanf("%d", &x);
- while(x != -1)
- {
- s = (btree *)malloc(sizeof(btree));
- s->data = x;
- s->left = NULL;
- s->right = NULL;
- insert(b,s);
- scanf("%d", &x);
- }
- }
- void inorder(btree *b)
- {
- if(b != NULL)
- {
- inorder(b->left);
- printf("%d ", b->data);
- inorder(b->right);
- }
- }
复制代码
下面是运行结果
$ ./a.out
5
1
4
3
2
-1
1 2 3 4 5
$ |
|