5.Palindrome Linked List
Input: head = [1,2,2,1]
Output: trueInput: head = [1,2]
Output: falseclass Solution
{
public:
ListNode *rev(ListNode *head)
{
if (!head || !head->next)
{
return head;
}
ListNode *prev = NULL;
ListNode *p = head;
ListNode *q = head;
while (p)
{
q = q->next;
p->next = prev;
prev = p;
p = q;
}
return prev;
}
bool isPalindrome(ListNode *head)
{
ListNode *p = head;
ListNode *q = head;
while (p && p->next)
{
p = p->next->next;
q = q->next;
}
if (p)
{
q = q->next;
}
q = rev(q);
p = head;
while (q)
{
if (q->val != p->val)
{
return false;
}
q = q->next;
p = p->next;
}
return true;
}
};Last updated

