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

发布于 2024-09-18 12:46:38 字数 412 浏览 5 评论 0原文

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

/** 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

水染的天色ゝ 2024-09-25 12:46:38

也许这样想会有所帮助:当前节点的节点数为 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.

看海 2024-09-25 12:46:38

让我们创建一个名为 countNodes(Node node) 的递归函数,

  1. 如果 nodenull,则意味着没有更多节点,因此 count = 0
  2. Else There是 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 是我们的答案。

Lets create a Recursive function called countNodes(Node node)

  1. If node is null, that means there are no more Nodes so count = 0
  2. Else There are 1 + countNodes(node.next)

Say you have a list 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))))

So, 4 is our answer.

落花随流水 2024-09-25 12:46:38

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文