Implement a function to check if a singly-linked list is a palindrome?

Though its an old post, I am posting a simple recursive solution that I wrote today while solving the same problem on Coding Interview preparation made easy:

int _isPalindrome(plist head, plist *res)
{
     int temp1 = 0;
    int temp2 = 0;

    if (head == NULL) return 1;

   
    if (head->next == NULL) {
           temp1 = ((*res)->val == head->val);
           *res = (*res)->next;
           return temp1;
    }

    temp1 = isPalindrome(head->next, res);
    temp2 = ((*res)->val == head->val);
    *res = (*res)->next;

     return temp1 && temp2;
}

int isPalindrome(plist head) {
     plist *temp;
     temp = &head;
     return _isPalindrome(head, temp);
}

3 Replies to “Implement a function to check if a singly-linked list is a palindrome?”

  1. The problem is how you can access the elements in backward order.

    There are 2 ways:

    – Using temporary structure to store, e.g., Stack

    – Change the linked list direction of right half then check for palindrome.

    Find our discussion and source code in Java for both approaches here http://www.capacode.com/data-str

Leave a Reply

Your email address will not be published. Required fields are marked *