Short python solution


  • 0
    Y
    class Solution(object):
        def isPalindrome(self, l):
            if not l or not l.next:
                return True
    
            # find the head of the second half of the list
            prev = ListNode('')
            prev.next = l
            curr = prev.next
            fast = l
            while fast and fast.next:
                fast = fast.next.next
                curr = curr.next
                prev = prev.next
    
            prev.next = None
    
            # now curr is the head of the second half, flip the second half
            head = None
            while curr:
                tmp = curr.next
                curr.next = head
                head = curr
                curr = tmp
    
            # compare two lists
            first, second = l, head
            while first and second:
                if first.val != second.val:
                    return False
                first, second = first.next, second.next
    
            return True

Log in to reply
 

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