Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 编写一个递归方法,计算链接节点链中的节点数_Java_Recursion_Linked List - Fatal编程技术网

Java 编写一个递归方法,计算链接节点链中的节点数

Java 编写一个递归方法,计算链接节点链中的节点数,java,recursion,linked-list,Java,Recursion,Linked List,我尝试了许多编码来解决下面的问题,但也找不到答案。谁能帮我解决我的问题,告诉我哪里是错误的编码 /** Task: Recusively counts the nodes in a chain. * @param start the first node * @returns the number of nodes in the linked chain */ public int countNodes(Node start) { if (start == null) // base cas

我尝试了许多编码来解决下面的问题,但也找不到答案。谁能帮我解决我的问题,告诉我哪里是错误的编码

/** Task: Recusively counts the nodes in a chain.
* @param start the first node
* @returns the number of nodes in the linked chain */
public int countNodes(Node start)
{
if (start == null) 

// base case

{
  countNodes (Node start);

// recursive case
else

System.out.println (start.data);
return start.next;
}
} // end countNodes

这样想可能会有所帮助:当前节点的节点数是1加上计算其余节点的结果

这样想可能会有所帮助:当前节点的节点数是1加上剩余节点的计数结果

在递归中,你不应该对下一个等式使用相同的参数,基本上,你应该做一些简单的计算,在你的例子中添加一个,然后用参数的“next”值再次调用你的函数。显然,为了能够使用递归解决这个问题,应该有可能从当前节点移动到下一个节点。

在递归中,你不应该对下一个方程使用相同的参数,基本上,你应该做一些简单的计算,在你的例子中添加一个,然后用“下一个”再次调用你的函数参数的值。显然,为了能够使用递归解决这个问题,应该有可能从当前节点移动到下一个节点。

让我们创建一个名为
countNodes(node-node)

  • 如果
    node
    null
    ,则表示没有更多节点,因此count=0
  • 否则有1+个countNodes(node.next)
  • 假设你有一个列表a->B->C->D->NULL

    countNodes(NodeA) = 1 + countNodes(NodeB)
    countNodes(NodeA) = 1 + (1 + countNodes(NodeC))
    countNodes(NodeA) = 1 + (1 + (1 + countNodes(NodeD)))
    countNodes(NodeA) = 1 + (1 + (1 + (1 + 0))))
    

    因此,4是我们的答案。

    让我们创建一个名为
    countNodes(Node Node)

  • 如果
    node
    null
    ,则表示没有更多节点,因此count=0
  • 否则有1+个countNodes(node.next)
  • 假设你有一个列表a->B->C->D->NULL

    countNodes(NodeA) = 1 + countNodes(NodeB)
    countNodes(NodeA) = 1 + (1 + countNodes(NodeC))
    countNodes(NodeA) = 1 + (1 + (1 + countNodes(NodeD)))
    countNodes(NodeA) = 1 + (1 + (1 + (1 + 0))))
    

    因此,4是我们的答案。

    请向我们展示您迄今为止所做的尝试,然后我们可以帮助您改进。如果这是家庭作业,请相应地标记:-)这是家庭作业还是什么?我相应地添加了
    家庭作业
    标记。请以后这样做。家庭作业的处理方式与“普通”问题稍有不同,因此-我们不做任何人的家庭作业,但如果我们看到您已经尽了自己的一份努力来解决问题,我们很高兴提供提示和更正:-)我写下的代码已经可以帮助我检查哪里做错了。非常感谢。请向我们展示您迄今为止所做的尝试,然后我们可以帮助您改进。如果这是家庭作业,请相应地标记:-)这是家庭作业还是什么?我相应地添加了
    家庭作业
    标记。请以后这样做。家庭作业的处理方式与“普通”问题稍有不同,因此-我们不做任何人的家庭作业,但如果我们看到您已经尽了自己的一份努力来解决问题,我们很高兴提供提示和更正:-)我写下的代码已经可以帮助我检查哪里做错了。非常感谢你。