I have a Single Linked List. I want to find that Linked List is Palindrome or not. I have implemented it in One way as below.
bool palindromeOrNot(node *head) {
node *tailPointer;
node *headLocal=head;
node *reverseList=reverseLinkedListIteratively(head);
int response=1;
while(headLocal != NULL && reverseList!=NULL) {
if(headLocal->id==reverseList->id) {
headLocal=headLocal->next;
reverseList=reverseList->next;
}
else
return false;
}
if(headLocal == NULL && reverseList==NULL)
return fasle;
else
return true;
}
I am reversing the original Linked List and then comparing Node by Node. If everything is fine then I will return 1 else return 0.
Is there a better algorithm to solve the problem.
When we compare the linked list to the reversed list, we can only actually need to compare the first half of the list. If the first half of the normal list matches the first half if the reverse list, then the second half of the normal list must match the second half of the reversed list.
Here is my solution to this problem. To test it I used integers instead of chars forexample I used 1,4,1,4,1 instead "adada". You can change int to char and everything should still be working