基于使用java的递归

Kri*_*ish 1 java recursive-datastructures

public void length() {
    System.out.println(length(head, 0));
}
public int length(Node he, int count) {
    if(he!=null) {
        // System.out.println(he.data +"   "+count++);
        // count++;
        // return length(he.next, count);
        return length(he.next, count++);
    }
    return count;
}
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我必须找到链表的长度.如果我运行相同的代码,我得到的长度为0.但是,当我使用注释代码,我得到正确的长度.为什么会这样?

Era*_*ran 5

length(he.next, count++)将原始值传递count给方法调用,因为您正在使用后增量运算符.因此,你总是传递0.

length(he.next, ++count)会工作,因为这里递增的值count将被传递.

在您的注释代码中,您没有将值传递count++给方法调用,而是count在它已经递增后传递,这也有效.