C语言中递归函数的数据采集
我正在写一个哈夫曼算法,在递归函数中收集数据时遇到了问题。这意味着我有一个递归函数,可以从树中生成代码,但我希望将它们放在数组中(这允许我以后处理数据)。我写了这个函数C语言中递归函数的数据采集,c,arrays,algorithm,recursion,C,Arrays,Algorithm,Recursion,我正在写一个哈夫曼算法,在递归函数中收集数据时遇到了问题。这意味着我有一个递归函数,可以从树中生成代码,但我希望将它们放在数组中(这允许我以后处理数据)。我写了这个函数 void save_code(HuffNode** array, int pos, HuffNode *node, char * table, int depth) { if(node->left == NULL){ printf("%d - %c > ", pos, node->sign);
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的变量数组中。整个程序如下所示:
编辑:
我问自己,全局变量是否能解决一个问题——在编码几分钟后——答案是肯定的
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);
}
}
我想问一下如何在调用之间收集递归函数中的数据。还有什么其他方法可以解决像这样的问题。通过指针传递它:
void save_code(..., int *pos)
{
// ...
// use and modify (*pos) as you desire
// ...
save_code(..., pos);
// ...
}
int save_code(..., int pos)
{
// ...
// use and modify pos as you desire
// ...
pos = save_code(..., pos);
// ...
return pos;
}
int pos = 0; // global variable
void save_code(...)
{
// ...
// use and modify pos as you desire
// ...
save_code(...);
// ...
}
这是一个很好的方法,只是它看起来不太漂亮-每个递归调用都有一个额外的参数,并且必须使用*pos
而不是pos
传递并返回它:
void save_code(..., int *pos)
{
// ...
// use and modify (*pos) as you desire
// ...
save_code(..., pos);
// ...
}
int save_code(..., int pos)
{
// ...
// use and modify pos as you desire
// ...
pos = save_code(..., pos);
// ...
return pos;
}
int pos = 0; // global variable
void save_code(...)
{
// ...
// use and modify pos as you desire
// ...
save_code(...);
// ...
}
我不建议这样做(至少不建议超过指针传递),因为您将返回并传递一个值,这似乎是不必要的,因为您只需要执行其中一个操作
您也不能对多个值使用这种方法,但是通过使用结构
很容易修复,尽管如果函数已经返回了一些内容,这会变得更加混乱
为完整起见,全局变量:
void save_code(..., int *pos)
{
// ...
// use and modify (*pos) as you desire
// ...
save_code(..., pos);
// ...
}
int save_code(..., int pos)
{
// ...
// use and modify pos as you desire
// ...
pos = save_code(..., pos);
// ...
return pos;
}
int pos = 0; // global variable
void save_code(...)
{
// ...
// use and modify pos as you desire
// ...
save_code(...);
// ...
}
这有一个缺点,即在全局范围内浮动一个pos
变量,但在许多情况下,通过将其设置为静态
,可以相当容易地将其修复,因此它仅限于一个文件,或者,在OOP世界中(例如,在C++中),可以将其作为私有类成员隐藏
使用全局变量可能是多线程的问题(即同时执行多个函数调用)
关于我的代码示例,我选择简洁而不是完整——我希望它们足够可读