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?

Write a small test case. If the answer's right across a few different test cases, your code is good! (It looks OK to me.)

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

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.

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?

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?

Yes, so do i return nothing, or do I just call the method?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.