Given a singly linked list, determine if it is a palindrome.

Follow up:

Could you do it in O(n) time and O(1) space?



1 /**
2 * Definition for singly-linked list.
3 * struct ListNode {
4 * int val;
5 * ListNode *next;
6 * ListNode(int x) : val(x), next(NULL) {}
7 * };
8 */
9 class Solution {
10 public:
11 bool isPalindrome(ListNode* head) {
12
13 vector<int> tmp;
14 while(head)
15 {
16 tmp.push_back(head->val);
17 head=head->next;
18 }
19 int left=0;
20 int right=tmp.size()-1;
21 while(left<right)
22 {
23 if(tmp[left]!=tmp[right])
24 return false;
25 left++;
26 right--;
27 }
28 return true;
29 }
30 };