java - 无法理解为什么计数没有增加

标签 java recursion data-structures

作为练习的一部分,我正在编写递归代码来计算队列中的节点数。我添加/修改的代码部分(在 NodeQueue.java 中)在这里:

public class NodeQueue implements Queue
{
    static protected int count;                 //for RecNodeCount method only
    protected Node beingCountedNode = head;     //for RecNodeCount method only

// other methods..

public int RecNodeCount()
    {
        if(beingCountedNode == null)
            return count;
        else
        {
            count++;
            beingCountedNode = beingCountedNode.getNext();
            return RecNodeCount();
        }
    }

整个代码如下:

队列.java:http://pastebin.com/raw.php?i=Dpkd8ynk

Node.java:http://pastebin.com/raw.php?i=Zy0KbrtJ

NodeQueue.java:http://pastebin.com/raw.php?i=j6hieiLG

SimpleQueue.java:http://pastebin.com/raw.php?i=vaTy41z4

我无法理解为什么即使在队列中加入了几个节点之后我的结果却为零。 size 变量返回正确的数字。我对 count 变量做了或多或少相同的事情(我认为!),即增加所需的变量。

最佳答案

虽然我相信该方法会起作用(如果在调用之前正确设置了beingCountedNode。请参阅@peter.petrov答案),但使用实例变量作为函数的参数是很奇怪的。我认为递归函数应该具有签名 int Count( Node node ) ,它返回给定 Node 之后(包括)的节点数。

// returns the number of nodes in the list
public int Count(){ return CountHelper( head ); }

// helper recursive function
// returns the number of nodes in the list after and including "node".
// call with head of the list to get the count of all nodes.
private int CountHelper( Node node )
{
    if( node == null )
       return 0;
    else
       return 1 + CountHelper( node.getNext() );
}

另请注意,在您当前的示例中,您从未重置 count,因此如果我连续调用 RecNodeCount() 两次,您的方法会告诉我计数是两次它到底是什么。编辑,实际上我想它不会,因为 beingCountedNode 将为 null,但这样做仍然很奇怪。

关于java - 无法理解为什么计数没有增加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22642231/

相关文章:

python - 如何在 Stackless Python 中进行无限(或非常深)递归?

c - 递归输出C

javascript - 如何优化包含重复值的组合?

algorithm - 为什么 Eric Lippert 的不可变二叉树中没有循环?

java - 如果存储在 concurrentHashMap 中,POJO 对象中的可变字段是否线程安全?

java - 导入javazoom无法解决

data-structures - 每个节点有两个子节点的树的节点数

java - 了解使用递归调用的二叉搜索树 (BST) 删除实现

java - 如何用 Java 浏览和显示 XML 内容

java - 黑莓工具栏 7.0