0

我的问题是什么?我试图总结列表,它总是返回 0

public static int sum(List<Integer> l, Node<Integer> pos, int sum)  
{  
    if(pos==null)  
        return 0;  
    sum=sum+pos.getInfo();  
    pos=pos.getNext();  
    return sum+sum(l, pos, sum);  
}

public static void main(String[] args) { 
    int sum=0; 
    List<Integer> l = new List<Integer>(); 
    Node<Integer> pos = l.getFirst(); 

    l = input(l, pos); 
    System.out.println(l); 
    System.out.println(sum(l, pos, sum)); 
} 

谢谢。

4

1 回答 1

2

您在评论中说您的呼叫站点如下:

public static void main(String[] args) {
    int sum = 0;
    List<Integer> l = new List<Integer>();
    Node<Integer> pos = l.getFirst();      //<======= `pos' refers to the empty list
    l = input(l, pos);
    System.out.println(l);
    System.out.println(sum(l, pos, sum));
}

问题在于,由于您pos在将任何内容添加到列表之前进行了初始化,因此您总是总结原始(空)列表。

于 2013-02-18T19:09:43.443 回答