简体   繁体   English

java中的链表递归求和function

[英]Recursive sum function for a linked list in java

I want to sum up all the values of a linked list recursively but it doesn't work.我想递归地总结链表的所有值,但它不起作用。 It says:它说:

Cannot invoke "Element.sum()" because the return value of "Element.getNext()" is null无法调用“Element.sum()”,因为“Element.getNext()”的返回值为 null

public class Element{
    private int value;
    private Element next;
}

public class MyList{
    private Element elements;
    public int sum(){
        if (elements == null) return 0;
            return elements.getValue() + elements.getNext().sum();
        }
    }
}

sum isn't even a method of Element , so the implementation shouldn't compile. sum甚至不是Element的方法,因此不应该编译实现。

I'd pass the root element to an internal sum method which can be recursive, and keep the no-arg sum method public:我会将根元素传递给可以递归的内部sum方法,并保持无参数sum方法公开:

public class MyList {
    private Element elements;

    public int sum() {
        return sum(elements);
    }

    private int sum(Element e) {
        if (e == null) {
            return 0;
        }
        return e.getValue() + sum(e.getNext());
    }
}

As it seems you are trying to learn about recursivity, and it seems you are really trying, I won't give you a complete solution here.由于您似乎正在尝试学习递归,并且您似乎真的在尝试,因此我不会在这里为您提供完整的解决方案。

First I think you didn't provide the complete code, because as is it does not compile.首先,我认为您没有提供完整的代码,因为它无法编译。 You are calling elements.getNext().sum() meaning you have a sum() method on your class Element.您正在调用elements.getNext().sum()意味着您在 class 元素上有一个 sum() 方法。

And this is actually one possible correct way, to have a sum method in you Element class, because you want recursivity to happen on every Element.这实际上是一种可能的正确方法,在元素 class 中使用求和方法,因为您希望在每个元素上都发生递归。

So as you started this way, you should continue to try this way: add a sum method on your Element class.因此,当您以这种方式开始时,您应该继续尝试这种方式:在 Element class 上添加 sum 方法。 And this is where you can do recursivity.这就是你可以进行递归的地方。 Recursivity meaning to call again the same method either on another instance or with another parameter...递归意味着在另一个实例上或使用另一个参数再次调用相同的方法......

The other answer works, but will you learn about recursivity just by copying it?另一个答案有效,但你会通过复制它来了解递归吗? I would suggest trying to do similar thing, but in the Element class, so you manage to do it by yourself我建议尝试做类似的事情,但在元素 class 中,所以你自己设法做到这一点

Here's a solution:这是一个解决方案:

public class MyList{

    private Element elements;
    
    class Element{
        private int value;
        private Element next;
        Element(int value) {
            this.value = value;
        }
        public Element getNext() {
            return next;
        }
        public int getValue() {
            return value;
        }
        public void setNext(Element next) {
            this.next = next;
        }
        public int sum() {
            if (next == null) {
                return value;
            } else {            
                return value + next.sum();
            }
        }
    }

    public MyList(int data[]) {
        Element prev = null;
        for (int value : data) {
            Element e = new Element(value);
            if (prev == null) {
                elements = e;
            } else {
                prev.setNext(e);
            }
            prev = e;
        }
    }
    
    public int sum() {
        return elements == null ? 0 : elements.sum();
    }
    
    public static void main(String args[]) {
        MyList list = new MyList(new int[]{ 1, 2, 3});
        System.out.printf("sum = %d\n", list.sum());
    }
}
public class Foo {

    public static void main(String[] args) {
        MyList myList = new MyList();

        for (int i = 1; i <= 10; i++)
            myList.add(i);

        System.out.println(myList.sum());   // 55
    }
}

final class MyList {

    private Element head;

    public void add(int value) {
        if (head == null)
            head = new Element(value);
        else {
            Element element = head;

            while (element.next != null)
                element = element.next;

            element.next = new Element(value);
        }
    }

    public int sum() {
        return head == null ? 0 : head.sum();
    }

    private static final class Element {

        private final int value;
        private Element next;

        public Element(int value) {
            this.value = value;
        }

        public int sum() {
            return value + (next == null ? 0 : next.sum());
        }
    }
}

I am a bit confused about the returning value when the list reaches zero size or empty.当列表达到零大小或为空时,我对返回值有点困惑。 I assume the returning value at that instance shall be zero, which replaces the cumulative result of the summation, but still the returned value is the same??我假设该实例的返回值应为零,它取代了求和的累积结果,但返回值仍然相同?

any elaboration is highly appreciated.任何阐述都受到高度赞赏。

please note the code below, formed in Kotlin language.请注意下面的代码,由 Kotlin 语言组成。

fun main()
{
    val aList = listOf<Int>(1, 2, 3, 4)
    val sumResult = sumListContents(aList)
    println(sumResult)
}

fun sumListContents(intNums: List<Int>): Int
{
    return if (intNums.isNullOrEmpty())
    {
        println("--------------$intNums-------------")
        0
    }
    else
    {
        println("${intNums[0]} $intNums sub list: ${intNums.subList(1, intNums.size)}")
        return intNums[0] + sumListContents(intNums.subList(1, intNums.size))
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM