If you use tail recursion to find the sum of linked lists, there will still be stack overflows.

problem description

there is an example, given a linked list

public class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}

I hope to calculate the sum of linked list elements by ordinary recursion and tail recursion, and verify that when there are enough linked list elements, stack overflow occurs in ordinary recursion, but not

in tail recursion.

related codes

The

add0 () method uses normal recursion. The, add () method uses tail recursion.

public int add0(ListNode node) {
    if (node == null) {
        return 0;
    }
    return node.val + add0(node.next);
}
public int add(ListNode node, int result) {
    if(node == null) {
        return result;
    }
    result += node.val;
    return add(node.next, result);
}

what result do you expect? What is the error message actually seen?

Test Code:

public void test() {
        ListNode node = new ListNode(0);
        ListNode temp = node;
        for (int i = 1; i < 1000000; iPP) {
            temp.next = new ListNode(1);
            temp = temp.next;
        }
        System.out.println(add(node, 0));
//        System.out.println(add0(node));
    }

when the elements in the linked list are large enough, both recursive methods report a stack overflow. Why? How to optimize tail recursion to avoid stack overflow?

Apr.22,2021

is written in the form of tail recursion, which is of no use. In order to really achieve optimization, we also need to add a tail recursion optimization mechanism to the compiler. It is clear that the java compiler does not compile and optimize tail recursive code.


jvm doesn't seem to support TCO in the first place, does it? I haven't watched java for a long time. If there are any mistakes, please correct them.

you can try python, there should be no problem.


java does not have tail recursive optimization.


suggests using Trampoline instead, that is, convert recursion to iteration

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e4dcef-594e9.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e4dcef-594e9.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?