Created
June 18, 2014 07:03
-
-
Save iamdipankarj/3a1163f7c7c2710589db to your computer and use it in GitHub Desktop.
code to check if a given linked list is palindrome
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
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