【问题标题】:Recursive Algorithm to count nodes less than the given value递归算法计算小于给定值的节点
【发布时间】:2019-05-15 10:04:03
【问题描述】:

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

 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_

【问题讨论】:

  • 得到结果后,你有没有运行你的程序并尝试调试它?

标签: c recursion data-structures linked-list


【解决方案1】:

短版:

如果值较小,则在结果中添加+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

【讨论】:

    【解决方案2】:

    恐怕您没有将threshold 发送给递归调用。

    recCount(front->next, front->info);
    

    而且我不确定为什么应该存在以下条件。

    if(count < threshold)  //as count is initialized to 0.
    

    递归示例:

     int recCount(LLNode *front, int threshold)
     {
        int count = 0;
    
        if(front == NULL)
        return 0 ;
    
        if (front->info < threshold)
        count++;
    
        count = count + recCount(front->next, threshold);
    
        return count;
     }
    

    【讨论】:

      猜你喜欢
      • 2020-09-04
      • 2023-03-24
      • 2020-02-21
      • 1970-01-01
      • 1970-01-01
      • 2011-05-15
      • 1970-01-01
      • 1970-01-01
      • 2011-08-05
      相关资源
      最近更新 更多