Search This Blog

Thursday, June 30, 2011

Palindrome implementation using recursion

My co-worker mentioned a problem of checking palindrome of the word that is made up with linked list. So basically each character is connected via linked list and the task is to find out if the given linked list contains a palindrome word.

This is pretty simple if we want to implement in a iterative way using some data structure such as stack. However, I find it worth trying to implement the code using recursion.

So the idea is that I need to pass two arguments and I need to somehow to keep one pointer pointing to one end and the other pointer to the other end. This way, as we traverse we move each pointer two different directions and compare the value. If the value does not match, the word is not a palindrome word.

With that then, let me show my function.



int palindrome(node **head, node *cur)
{
int ret = 1;
if (cur) {
ret = palindrome(head, cur->next);
if (cur->data != (*head)->data) {
cout << cur->data << "-" << (*head)->data << ": not a palindrome" << endl;
ret = 0;
}
*head = (*head)->next;
}
return ret;
}


I think that recursion is one of those techniques that every programmer should be comfortable with and if I find more problems on recursion, I will work on it and post it here again.

No comments:

Post a Comment