Given a singly linked list, determine if it is a palindrome.
注解:用快慢指针找出中间节点,将后半链表倒序,对比每个节点
优化:找中间节点时,翻转前半段链表
bool isPalindrome(ListNode* head) {
if( !head || !head->next )
return true;
ListNode *fast = head, *slow = head;
while( fast->next && fast->next->next )
{
slow = slow->next;
fast = fast->next->next;
}
if( fast->next != NULL )
{
fast = slow->next;
slow = reverse( head, fast );
}
else
{
fast = slow->next;
slow = reverse( head, slow );
}
while( slow && fast )
{
if( slow->val != fast->val )
return false;
slow = slow->next;
fast = fast->next;
}
return true;
}
ListNode* reverse( ListNode* head, ListNode* tail )
{
if( head == tail || head->next == tail )
return head;
ListNode *p = head->next, *q;
head->next = NULL;
while( p != tail )
{
q = p->next;
p->next = head;
head = p;
p = q;
}
return head;
}