0

Hi
I have a method that has a reference to a linked list and an int that is the value. I want to recursively call that value to count and return how often that value is in the linked list.
So, here is what I got:

public static int find(LinkedNode x, int value){
if (x.value != value){
 return 0;
}
else{
 return 1+ find(x.next, value);
}
}

is that right?

3
Contributors
6
Replies
7
Views
8 Years
Discussion Span
Last Post by TigerGirl
0

i tried testing, but it keeps giving java.lang.StackOverflowError. How do I fix this?

0

Maybe you have all non-zero values?
You also need to check that x.next() refers to a real node, so you can stop recursing when you reach the end of the list.

0

Yeah, I that is true, I put in all numbers, but even I put in some zeros it still shows that? what are you supposed to input in the linked list?

0

You just want to count how many times a value is in the linked list? If so, I don't see how your method could work.

if (x.value != value){
return 0;
}

The first time the value isn't at the node, it will stop, even if the value is found at some later node in the list. Right?

Edited by BestJewSinceJC: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.