编写一个递归方法来计算链接节点链中的节点数
我尝试了很多编码来解决下面的问题,但也找不到答案。谁能帮我解决我的问题并告诉我哪里编码错误?
/** 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
I try many coding to solve the question bellow but also cannot find the answer. Can anyone help me solve my problem and tell me where is the wrong coding??
/** 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
也许这样想会有所帮助:当前节点的节点数为 1 加上其余节点的计数结果。
Perhaps it helps to think of it like this: the number of nodes is 1 for the current node plus the result of counting the rest of the nodes.
让我们创建一个名为
countNodes(Node node)
的递归函数,node
为null
,则意味着没有更多节点,因此 count = 0假设你有一个列表 A->B->C->D->NULL
所以,4 是我们的答案。
Lets create a Recursive function called
countNodes(Node node)
node
isnull
, that means there are no more Nodes so count = 0Say you have a list A->B->C->D->NULL
So, 4 is our answer.
在递归中,您不应该对下一个方程使用相同的参数,基本上,您应该做一些简单的计算,在您的情况下添加一个,然后使用参数的“下一个”值再次调用您的函数。显然,为了能够使用递归解决这个问题,应该有可能从当前节点移动到下一个节点。
In recursion you shouldn't use the same argument for the next equation, basically, you should do some simple calculation, in your case add one, and call your function again with the "next" value of the argument. Obviously, to be able to solve this problem using recursion, there should be possibility to move from the current node to the next one.