LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 653|回复: 2

出现段错误, 大家帮我看一下

[复制链接]
发表于 2007-4-27 10:40:58 | 显示全部楼层 |阅读模式
#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);

  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);
  }
}

应该怎么改?
发表于 2007-4-27 11:44:12 | 显示全部楼层
Post by litao19
#include <stdio.h>
应该怎么改?

关键在于,C 中参数都是传值。如果你想在被调函数中修改调用函数中某变量的值,就要把该变量的地址传进去。参考下列代码

  1. #include <stdio.h>
  2. #include <stdlib.h>

  3. typedef struct bnode
  4. {
  5.     int data;
  6.     struct bnode *left, *right;
  7. }btree;

  8. void creat(btree **b);
  9. void insert(btree **b, btree *s);
  10. void inorder(btree *b);

  11. int main()
  12. {
  13.     btree *b;

  14.     creat(&b);
  15.     inorder(b);

  16.     printf("\n");

  17.     return 0;
  18. }

  19. void insert(btree **b, btree *s)
  20. {
  21.     if(s == NULL) return;
  22.     else if(*b == NULL) *b = s;
  23.     else if((*b)->data == s->data) return;
  24.     else if((*b)->data > s->data) insert(&(*b)->left, s);
  25.     else if((*b)->data < s->data) insert(&(*b)->right, s);
  26. }

  27. void creat(btree **b)
  28. {
  29.     int x;
  30.     btree *s;
  31.     *b=NULL;

  32.     scanf("%d", &x);
  33.     while(x != -1)
  34.     {
  35.         s = (btree *)malloc(sizeof(btree));
  36.         s->data = x;
  37.         s->left = NULL;
  38.         s->right = NULL;
  39.         insert(b,s);
  40.         scanf("%d", &x);
  41.     }
  42. }

  43. void inorder(btree *b)
  44. {
  45.     if(b != NULL)
  46.     {
  47.         inorder(b->left);
  48.         printf("%d ", b->data);
  49.         inorder(b->right);
  50.     }
  51. }
复制代码

下面是运行结果
$ ./a.out
5
1
4
3
2
-1
1 2 3 4 5
$
回复 支持 反对

使用道具 举报

 楼主| 发表于 2007-4-27 14:18:19 | 显示全部楼层
非常感谢,MMMIX
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表