一种递归算法,用于添加非伪头单链线性列表的所有元素.只有列表的头才会作为参数给出



我在添加单链表的元素时遇到运行时错误。我已经输入了错误图片的图片描述。我在这里附上我的代码:

public class Node{
Node next;
int a=0;

public Node (int e, Node n){
a =e;
next =n;
}}


public class Question6{
static int sum=0;
public static void main(String[]args){

Node head=null;

Node n5= new Node(5,null);
Node n4= new Node(4,n5);
Node n3= new Node(3,n4);
Node n2= new Node(2,n3);
Node n1= new Node(1,n2);

head=n1;
sum =add(head);   
}
public static int add(Node head){
if(head==null){
return sum;
}
else{
sum=sum + head.a;
head=head.next;
add(head);
}
return sum;
}
}

您的编译器似乎出了问题。图像中的错误表明在类Node中找不到init方法。尝试在类Node:中添加空的init方法(花括号(

class Node{
Node next;
int a = 0;
{}
public Node(int e, Node n) {
a = e;
next = n;
}
}

首先,您的代码不是real递归,因为您使用了external static variable

public static int sum(Node head) {
return sum(head, 0);
}
private static int sum(Node node, int sum) {
return node == null ? sum : sum(node.next, sum + node.a);
}

最新更新