【发布时间】: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