0

I want the recursive function to check the value in the current node equals the value in the next node and increment by 1 else don't increment and move on until the end of the list. So for, a list of 1, 2, 2, 3 , 1, 1. It should return 2 as 2, 2 is one adjacent duplicate and 1, 1 is another adjacent duplicate.

I can't figure out how to handle the false case when the value of the current isn't equal to the value of the next. Basically, not incrementing.

This is my code so far...

int fn(Node l) {
    if (l == null)
        return 0;
    else 
        return (l.value == l.next.value) ? (1 + fn(l.next)) : ;
}
2
  • I'm not sure what you are trying to accomplish. Could you please provide a better description of what you are trying to do? Commented Oct 13, 2012 at 18:04
  • If the value in the current node = value in the next node increment by 1 else don't increment and move on until the end of the list. So for, a list of 1, 2, 2, 3 , 1, 1. It should return 2. 2,2 repeats and 1,1 repeats. Commented Oct 13, 2012 at 18:07

1 Answer 1

2

The function needs to be called again in either case, for the false case you would not add 1 to the return value, i.e.

return (l.value == l.next.value) ? (1 + fn(l.next)) : fn(l.next);

You should also check that the l.next is not null first. So you could rewrite the function...

int fn(Node l) {
   if (l == null || l.next == null)
       return 0;
   return (l.value == l.next.value ? 1 : 0) + fn(l.next);
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.