Reputation: 11
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.
Upvotes: 1
Views: 1528
Reputation: 41378
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);
}
}
Upvotes: 4
Reputation: 14234
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).
Upvotes: 1