【问题标题】:Collecting data in recursion function in C在 C 中的递归函数中收集数据
【发布时间】:2014-04-02 18:11:39
【问题描述】:

我正在编写一个霍夫曼算法,但在递归函数中收集数据时遇到了问题。这意味着我有一个从树生成代码的递归函数,但我想将它们放在数组中(这允许我稍后处理数据)。我写了函数

void save_code(HuffNode** array, int pos, HuffNode *node, char * table, int depth)
{
  if(node->left == NULL){
    printf("%d - %c > ", pos, node->sign);

    array[pos]->sign = node->sign;
    strcpy(array[pos]->code, table);

    puts(table);
    // save to global table
  }
  else {
    table[depth] = '0';
    save_code(array, pos + 1, node->left, table, depth + 1);
    table[depth] = '1';
    save_code(array, pos + 1 , node->right, table, depth + 1);
  }
}

变量 pos 最大的问题是,我想如果我可以增加 pos 变量(比如在循环中),那么我就可以将它保存在位置 pos 的变量数组中。整个程序在这里:https://github.com/mtczerwinski/algorithms/blob/master/huffman/huffman.c

编辑: 我问自己全局变量是否可以解决问题——经过片刻的编码——答案是肯定的。

int pos = 0; // global variable
void save_code(HuffNode** array, HuffNode *node, char * table, int depth) {
  if(node->left == NULL){
    array[pos]->sign = node->sign;
    strcpy(array[pos]->code, table);
    pos++;
  }
  else {
    table[depth] = '0';
    save_code(array , node->left, table, depth + 1);
    table[depth] = '1';
    save_code(array, node->right, table, depth + 1);
  }
}

我想问如何在调用之间的递归函数中收集数据。还有什么其他方法可以解决这样的问题。

【问题讨论】:

    标签: c arrays algorithm recursion


    【解决方案1】:

    通过指针传递:

    void save_code(..., int *pos)
    {
      // ...
      // use and modify (*pos) as you desire
      // ...
      save_code(..., pos);
      // ...
    }
    

    这是一个很好的方法,只是它看起来不太漂亮 - 每个递归调用都有一个附加参数,并且必须使用 *pos 而不是 pos

    传递并返回:

    int save_code(..., int pos)
    {
      // ...
      // use and modify pos as you desire
      // ...
      pos = save_code(..., pos);
      // ...
      return pos;
    }
    

    我不会真的推荐这个(至少不是通过指针传递),因为你会返回并传递一个值,这似乎没有必要,因为你只需要做其中之一。

    您也不能对多个值使用这种方法,但使用struct 很容易修复,尽管如果函数已经返回某些内容,这会变得相当混乱。

    并且,为了完整起见,全局变量:

    int pos = 0; // global variable
    void save_code(...)
    {
      // ...
      // use and modify pos as you desire
      // ...
      save_code(...);
      // ...
    }
    

    这具有在全局范围内浮动的pos 变量的缺点,但在许多情况下,通过将其设置为static 可以很容易地修复它,因此它仅限于一个文件,或者在OOP 中世界(例如在 C++ 中),可以将其隐藏为私有类成员。

    使用全局变量会成为多线程的问题(即同时执行多个函数调用)。


    在我的代码示例方面,我选择简洁而不是完整性 - 我希望它们足够可读。

    【讨论】:

      猜你喜欢
      • 2013-12-07
      • 1970-01-01
      • 2013-04-21
      • 1970-01-01
      • 2011-01-17
      • 1970-01-01
      相关资源
      最近更新 更多