Java How to find a value in a linked list iteratively and recursively

Posted by Roxy on Stack Overflow See other posts from Stack Overflow or by Roxy
Published on 2009-10-10T05:44:48Z Indexed on 2010/05/20 14:10 UTC
Read the original article Hit count: 152

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?

© Stack Overflow or respective owner

Related posts about linked-list

Related posts about java