Problem
Given the head of a singly linked list, return true if it is a palindrome or false otherwise.
Algorithm
Use a double-step pointer to find the start of the second half of the linked list (skip if counting), reverse the second half, then compare elements for validation.
Code
python3
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
if not head or not head.next:
return True
p1, p2 = head, head
while p2 and p2.next:
p1 = p1.next
p2 = p2.next.next
if p2:
p1 = p1.next
p3, p4 = p1, None
while p3:
p0 = p3.next
p3.next = p4
p4 = p3
p3 = p0
p1, p2 = head, p4
while p2:
if p1.val != p2.val:
return False
p1, p2 = p1.next, p2.next
return True