My this solution is showing TLE . But I dont know why…??? since it is O(n) solution only…PLEASE HELP.
Approach: I iterate through the linked list and form a string of its elements . I form another string with elements in reverse order … if they are same then it is a palindrome ,otherwise not. Have a look at the code,
class Solution {
public:
bool isPalindrome(ListNode* head) {
ListNode*temp=head;
string s1="";
string s2="";
s1+=char('0'+temp->val);
s2+=char('0'+temp->val);
while(temp->next!=NULL)
{
temp=temp->next;
s1+=char('0'+temp->val);
s2=char('0'+temp->val)+s2;
}
//cout<<s1<<endl;
// cout<<s2<<endl;
if (s1==s2)
return true;
else
return false;
}
};