我的问题是什么? 我试图对列表求和,它总是返回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));
}
感谢。
答案 0 :(得分: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
,因此总是总结原始(空)列表。