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

Example 1:

Input: 1->2
Output: false

Example 2:

Input: 1->2->2->1
Output: true

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

题解:

比较主流的解法是找到链表中点,然后翻转后半部分,再判断前半部分和后半部分是否一致。

class Solution {
public:
bool isPalindrome(ListNode* head) {
string s, rs;
ListNode *pre = NULL, *rehead = head;
while (head != NULL) {
rehead = head;
s += to_string(head->val);
head = head->next;
rehead->next = pre;
pre = rehead;
}
while (rehead != NULL) {
rs += to_string(rehead->val);
rehead = rehead->next;
}
return rs == s;
}
};