Problem
Implement a function to check if a linked list is a palindrome.
Example1
Input: 1->2
Output: false
Example2
Input: 1->2->2->1
Output: true
Solution
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(!head || !head->next)
return true;
ListNode *cur = head;
vector<int> vals;
while(cur)
{
vals.push_back(cur->val);
cur = cur->next;
}
int i = 0;
int j = vals.size() - 1;
while(i < j)
{
if(vals[i] != vals[j])
{
return false;
}
else
{
++i;
--j;
}
}
return true;
}
};