我有以下代码:

static int countStu = 0;

public static int countStudent(Node<Student> lst) {
    // pre : true
    // post : res = number of students in list
    if (lst != null) {
        countStu++;
        countStudent(lst.getNext());
    }
    return countStu;
}


该方法的问题是我必须在countStu方法之外声明countStudent(),这在我想两次调用countStudent()的情况下不好,它将使返回值加倍。我该如何解决此问题并能够无限次拨打countStudent()并获得正确的结果?

最佳答案

而是return((lst == null)? 0 : (1 + countStudent(lst.getNext())))

10-06 13:51