Skip to content

Instantly share code, notes, and snippets.

@iamdipankarj
Created June 18, 2014 07:03
Show Gist options
  • Save iamdipankarj/3a1163f7c7c2710589db to your computer and use it in GitHub Desktop.
Save iamdipankarj/3a1163f7c7c2710589db to your computer and use it in GitHub Desktop.
code to check if a given linked list is palindrome
/**
Reverse a Singly Linked List
Helper function
**/
Node *ReverseList(Node **head)
{
Node *prev = NULL;
Node *temp = *head;
Node *next;
while(temp != NULL)
{
next = temp->next;
temp->next = prev;
prev = temp;
temp = next;
}
*head = prev;
return *head;
}
bool isPalindrome(Node *head) {
Node *temp = head;
Node *orig_list = head;
Node *rev_list = NULL;
int index;
for(index = 1; index < getNodeCount(head)/2; index++){
temp = temp->next;
}
rev_list = ReverseList(&temp);
while(orig_list != NULL && rev_list != NULL){
if(orig_list->data != rev_list->data ){
return false;
}
orig_list = orig_list->next;
rev_list = rev_list->next;
}
/// Free memory
delete rev_list;
delete orig_list;
/// If we reach here the the list is palindrome
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment