首页 > 解决方案 > 递归算法计算小于给定值的节点

问题描述

你好,我正在准备期末考试,所以从我之前的考试中,我得到了这个问题的部分学分。递归算法,以便计算给定链表中有多少节点的信息值小于给定阈值

 typedef struct LLNode {
       int info;
       struct LLNode* pNext;
    }LLNode;

    int recCount(LLNode *front, int threshold)
     {  


     }

我的回答是

int count = 0;
int total_less;
if(front == NULL)
 return 0 ;
if(count < threshold) 
   count = 1 + recCount(front->next, front->info); 
   total_less++;

return total_

标签: crecursiondata-structureslinked-list

解决方案


较短的版本:

如果 value 较小,则将 +1 添加到结果并检查列表中的下一个节点,否则只检查下一个节点而不添加到计数。

int recCount(struct NODE *N, int value)
{
    if(N == NULL)
        return 0;

    if(N->data < value)
        return 1 + recCount(N->next, value);

    return recCount(N->next, value);
}

示例代码: http ://tpcg.io/36qFkO


推荐阅读