代码之家  ›  专栏  ›  技术社区  ›  Comp

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

  •  -3
  • Comp  · 技术社区  · 8 年前

    我有一个问题,关于如何编写一个函数,它将为我提供手动链表中元素的总和。我试过这样做,但不起作用: 函数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;
            }
    }
    
    2 回复  |  直到 7 年前
        1
  •  2
  •   daniu    8 年前

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

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

    具有

    class MyList {
        public Node head();
    } 
    
    class Node {
        public int value() ;
        public Node next() ;
    } 
    
        2
  •  1
  •   AhmadReza    8 年前

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

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