Clear Python beats 98%


  • 0
    C
    class Solution(object):
        def isPalindrome(self, head):
            if not head:
                return True
            fast = slow = head
            prev = None
            while fast.next and fast.next.next:
                fast = fast.next.next
                nn = slow.next
                slow.next = prev
                prev = slow
                slow = nn
            # if even number of nodes in linked list, we have one more node to reverse
            if fast.next:
                nn = slow.next
                slow.next = prev
                prev = slow
                slow = nn
            # if odd number of nodes in the linked list, slow is right at the middle which contains an irrelevant value for the palindrome
            else:
                slow = slow.next
            
            while slow:
                if slow.val != prev.val:
                    return False
                slow = slow.next
                prev = prev.next
            return True
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.