“手动”链表java中的元素总和

“手动”链表java中的元素总和,java,Java,我有一个关于如何编写一个函数的问题,该函数将为我提供手动链表中元素的总和。我试过这样做,但不起作用: 函数insert在列表中插入元素 public class list { int head; List tail; int sum=0; int value; public void insert(int elt){ if(tail == null){

我有一个关于如何编写一个函数的问题,该函数将为我提供手动链表中元素的总和。我试过这样做,但不起作用: 函数insert在列表中插入元素

public class list {
            int head;
            List tail;
            int sum=0;
            int value;
    public void insert(int elt){
        if(tail == null){

            tail = new list();
            tail.head = elt;

        }
        else{
        tail.insert(elt);
        }
    }
    public int sum(list head){
            if(head!=null){
                sum += head;
                return tail.sum(head);
            }
            return sum;
        }
}

为什么不使用java中的List对象? 您可以将此函数用于列表中元素的总和:

public static int sum (List<Integer> list) {
    int sum = 0;
    for (int i: list) {
        sum += i;
    }
    return sum;
}

这类事情的代码(即手动链表迭代)如下所示:

public int calculateSum(MyList list) {
    Node node = list.head();
    int sum = 0;
    while (node != null) {
        sum += node.value();
        node = node.next();
    }
    return sum;
}


最好使用英文命名变量,Seznam不是已知的类型。它是类的名称:public class Seznam{没有告诉我们任何事情,我们不知道它是什么。请看和。这是内部类Seznam吗?是的,它是@Lalit VermaCould。请编写整个函数,这样我就知道函数中需要哪些参数了。不过,您需要自己编写MyList和Node类。
class MyList {
    public Node head();
} 

class Node {
    public int value() ;
    public Node next() ;
}