https://leetcode.com/problems/palindrome-linked-list/
反转链表的前半部分 反转完后从中间开始向两边比较
class Solution {
public:
bool isPalindrome(ListNode* head) {
if (!head)
return true;
int count = 0;
ListNode *tmp, *p1, *p2;
tmp = head;
while (tmp)//count the size of the list
{
count++;
tmp = tmp->next;
}
int mid = 0;
p2 = head;
p1 = NULL;
while (mid < count / 2)//reverse the first half of the list
{
tmp = p2->next;
p2->next = p1;
p1 = p2;
p2 = tmp;
mid++;
}
if (count % 2 != 0)
p2 = p2->next;
while (p2)
{
if (p2->val != p1->val)
return false;
p2 = p2->next;
p1 = p1->next;
}
return true;
}
};