c - 如何使交互式链表函数递归
问题描述
我在寻找使迭代函数成为递归函数的方法时遇到了这个问题。
它是关于一个链表,这个链表存储了“收藏”的视频,每个视频都有一个声音,我们要统计所有包含指定声音的视频。
链表元素如下所示:
typedef struct {
tVideo video;
} tFavorite;
// Data type to hold data related to a video in the platform
typedef struct tNode {
tFavorite e;
struct tNode *next;
} tFavoriteStackNode;
// Definition of a stack of favorites
typedef struct {
tFavoriteStackNode *first;
} tFavoriteStack;
并且 tVideo 有声音(video.sound)。
现在,迭代函数是这样的:
unsigned favoriteStack_getFavoritesPerSoundRecursive(tFavoriteStack *stack, tSound *sound){
// PR2 EX3
assert(stack != NULL);
tFavoriteStackNode *tmp = (tFavoriteStackNode*)malloc(sizeof(tFavoriteStackNode));
static int cont = 0;
if (favoriteStack_empty(*stack)) {
return cont;
}
else {
tmp = stack->first;
while (tmp != NULL) {
if (tmp->e.video.sound != NULL){
if (sound_equals(sound, tmp->e.video.sound)){
cont++;
}
}
tmp = tmp->next;
}
}
return cont;
}
在这种情况下,我们做一个while循环,每次都将节点更改为下一个。
(请注意,if (tmp->e.video.sound != NULL)
由于 sound_equals() 中的断言而被调用)
所以我的问题是我怎样才能把这个函数变成一个递归函数?
提前致谢,
琼·弗雷克斯
解决方案
unsigned tFavoriteStackNode_numSoundRecursive (
tFavoriteStackNode *node,
tSound *sound
){
if (node == NULL) // stop recursion
return 0;
// assuming sound_equals returns a boolean value (0: false, 1: true)
// need something different if a e.g. -1 could be returned in case of some error
unsigned eq = (node->e.video.sound != NULL)
? sound_equals(sound, node->e.video.sound)
: 0;
return (
eq +
tFavoriteStackNode_numSoundRecursive (
node->next,
sound
)
);
}
unsigned favoriteStack_getFavoritesPerSoundRecursive (
tFavoriteStack *stack,
tSound *sound
){
assert(stack != NULL);
if (favoriteStack_empty(*stack)) //sure about dereferencing?
return 0;
return tFavoriteStackNode_numSoundRecursive(stack->first);
}
@Code Apprentice - 递归终止得太早了,我意识到,现在应该是正确的。
推荐阅读
- angular - 如何使用一个组件上的按钮将项目从集合中删除到另一个?
- regex - 有没有办法在同一个正则表达式中重用正则表达式子表达式(非连续)?
- java - 输入错误。即使在接受新输入后仍使用旧输入
- spring - 防止组件扫描进行单元测试
- sql - SQL中分组时间序列的最小值和最大值
- django - 如何计算外键中的项目?
- linux - 搜索文件夹中的所有子文件夹时,获取“ [:if-then:意外运算符”
- javascript - PHP - 安全地允许用户保存 html
- bonjour - 我正在尝试为 _universal._sub._ipp.tcp.local 生成 dns-sd 查询,有没有办法请求子查询
- elasticsearch - Elasticsearch 中的请求时间和搜索延迟持续飙升