234. Palindrome Linked List

234. Palindrome Linked List

[Easy] “Given a singly linked list, determine if it is a palindrome."

Link to Leetcode

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: ListNode) -> bool:
        slow = head
        fast = head
        rev = None

        # capture reversed list until middle
        while fast and fast.next:
            fast = fast.next.next
            prev = rev
            rev = slow
            slow = slow.next
            rev.next = prev
        # odd length list
        if fast:
            slow = slow.next
        while rev and (rev.val == slow.val):
            slow = slow.next
            rev = rev.next
        return not rev