Check if a Linked List Is a Palindrome
Implement isPalindrome
Given the head of a singly linked list, determine whether it reads the same forwards and backwards.
The optimal solution can't just compare from both ends the way an array would, since a singly linked list has no backward pointer to walk in reverse. Instead it finds the middleSlow/Fast Pointer Middle-FindingAdvance one pointer twice as fast as another. When the fast pointer reaches the end, the slow pointer is exactly at the middle — in a single pass, no length count needed. with slow and fast pointers, reverses everything from the middle onward, and then walks two pointers outward — one across the untouched front half, one across the newly-reversed back half — checking that every pair of values matches. If they all match, it's a palindrome.
Example 1:
Input: head = [1,2,2,1]
Output: true
Example 2:
Input: head = [1,2]
Output: false
Example 3:
Input: head = [1]
Output: true
+ 5 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ number of nodes in head ≤ 500 - ●
-100 ≤ node value ≤ 100
head =
[1, 2, 2, 1]