1

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.

3
  • Which specific programming language? Commented Nov 4, 2009 at 23:16
  • It looks like its a Java or C# question, given the context and the return value. (C++ is very unlikely given the context) Commented Nov 4, 2009 at 23:19
  • Yes! you are correct its Java. Commented Nov 4, 2009 at 23:21

2 Answers 2

4

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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).

1 Comment

Depending on the JIT compiler's ability to do tail-recursion optimization, recursively processing a long linked list can result in a stack overflow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.