views:

324

answers:

3

Hi everyone. So, I was reading about linked lists and recursion. I just wanted to know why can't I use recursion in a method that is static void? Also, I was wondering in Java in the linked list recursion, why you can use static void in printing or search for the nodes. Thank you.

+1  A: 

You can use a static method when using recursion. You just have to pass in all of the information that is necessary to work inside the function. With Linked lists recursion is strongly encouraged because of how they are designed (each node contains a reference to the next node and (sometimes) its previous).

monksy
Depending on the JIT compiler's ability to do tail-recursion optimization, recursively processing a long linked list can result in a stack overflow.
Stephen C
+4  A: 

You can use recursion in a function that's static void. It just has to return its value or do what it's supposed to do via side-effects, which is often considered harmful. But for printing it makes perfect sense.

static void printList(node)
{
    if (node != null)
    {
        print(node);
        printList(node.next);
    }
}
JSBangs
+1  A: 

never mind my answer was wrong

bic bic