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.
In java,Store the value in string variable and reverse using string builder
the python program to check the input linked list is palindrome or not
Transverse through the first half and put it in stack and traverse the remaining half and pop from the stack simultaneously and check both are same or not. If both are same throughout then it is palindrome, else not.
I think you could get a better solution in terms of having O(1) memory usage and the same O(n) speed. By working with the linked list in place. You don't necessary have to create a reversed copy of the linked list. However this methods destroys the list. You will have to stitch it back into place, but the running time will still be O(n).
The code for the fast version of isPalindrome basically finds the middle of the linked list, then logically chunks the linked list into 2 pieces. It reverses only the first piece in place and compares it with the other piece. The bad part is it destroys the linked list due to the in place reversal on the first linked list chunk. However you can stitch the lists back together in place and still be in O(n) time.
The function to look at is isPalindromeFast. I started but haven't finished stitchlistsbacktogether. You can run the code in Go play here http://play.golang.org/p/3pb4hxdRIp .
Here is full code in Go.
I have implemented a solution to this problem using recursion.
Palindrome check of a linked list using recursion: