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?
要求时间复杂度为n,想了一下只能用快慢两个指针做,先找到中点,然后倒置后面一半链表比较。写的过程中放了好多低级错误,基础还是要加强啊。
class Solution {
public:
bool isPalindrome(ListNode* head) {
if (head == NULL)
{
return true;
}
ListNode *quick = head;
ListNode *slow = head;
while (quick->next && quick->next->next)
{
quick = quick->next->next;
slow = slow->next;
}
ListNode *left = head;
ListNode *right = revert(slow);
while (left != NULL)
{
if (left->val != right->val)
{
return false;
}
left = left->next;
right = right->next;
}
return true;
}
ListNode* revert(ListNode *head)
{
ListNode *p = head->next;
ListNode *q = head;
while (p != NULL)
{
ListNode *r = p->next;
p->next = q;
q = p;
p = r;
}
head->next = NULL;
return q;
}
};