Python readable solution


  • 0
    J
    import math
    
    class Solution(object):
    
        def length(self, head):
            res = 0 
            while head:
                res += 1
                head = head.next
            return res 
    
        def reverse(self, head):
            before, curr = None, head
            while curr:
                next = curr.next
                curr.next = before
                before, curr = curr, next
            return before
    
        def get_second_head(self, head, length):
            second_head = head
            for _ in range(int(math.ceil(length / 2.))):
                second_head = second_head.next
            return self.reverse(second_head)
    
        def isPalindrome(self, head):
            """ 
            :type head: ListNode
            :rtype: bool
            """
            length = self.length(head)
            second_head = self.get_second_head(head, length)
            while second_head is not None:
                if head.val != second_head.val:
                    return False
                head, second_head = head.next, second_head.next
            return True
    

Log in to reply
 

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