Java How to find a value in a linked list iteratively and recursively
- by Roxy
Hi
I have a method that has a reference to a linked list and a int value. So, this method would count and return how often the value happens in the linked list. So, I decided to make a class,
public class ListNode{
public ListNode (int v, ListNode n) {value = v; next = n;)
public int value;
public ListNode next;
}
Then, the method would start with a
public static int findValue(ListNode x, int valueToCount){
// so would I do it like this?? I don't know how to find the value,
// like do I check it?
for (int i =0; i< x.length ;i++){
valueToCount += valueToCount;
}
So, I CHANGED this part, If I did this recursively, then I would have
public static int findValue(ListNode x, int valueToCount) {
if (x.next != null && x.value == valueToCount {
return 1 + findValue(x, valueToCount);}
else
return new findvalue(x, valueToCount);
SO, is the recursive part correct now?