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.
Below is my implementation using vectors. Hope it helps someone.
node.h file as below
node.cpp file below.
main.cpp file below.
You can also check it using arrays, First traverse the linklist from its root and store the data field of every node into an array and then reverse that array and then compare both array one by one element. Below is the program
There is a couple of ways to do it. One of the solutions can be like below :
This solution has O(n) time complexity. Here is a sample implementation in C#.
Recursive algorithm implementation. The intention is just to make use of the natural recursion stack.
Why are you Making it complex. Since this is a home work.i can just give you a simple suggestion. I observe that you are only comparing the id's in your code. let's say your id is a char,why dont you simply traverse the list once and store the char's in an array and then check the for palindrome. your way simply reverses the linked list once and traverse the linked list twice totally there are three traversals in the function.
I am using a stack to store the characters until the halfway point of the list. Then, I check the characters in the second half of the list against the top of the stack. Time: O(n), Space: O(n/2)