-2

I have a question about how to write a function that will give me the sum of elements in a manual linked list. I tried it like this but it doesn't work: function insert() inserts elements in list.

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;
        }
}
Comp
  • 134
  • 2
  • 14

2 Answers2

2

Code for this kind of things (ie "manual" linked list iteration) is like this :

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

With

class MyList {
    public Node head();
} 

class Node {
    public int value() ;
    public Node next() ;
} 
daniu
  • 14,137
  • 4
  • 32
  • 53
1

Why don't you use List Object from java ? You can use this function for sum of elements in a list :

public static int sum (List<Integer> list) {
    int sum = 0;
    for (int i: list) {
        sum += i;
    }
    return sum;
}
Ahmadreza
  • 939
  • 1
  • 9
  • 13