One Python Solution


  • 3
    Y

    One python solution

    #class Solution(object):
    def isPalindrome(self, head):
    """
    :type head: ListNode
    :rtype: bool
    """

        #bound consideration
        if not head or not head.next:
            return True
            
        #find the head of the second half part
        fast = head;
        slow = head;
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
        #slow now is the head of second half
        
        #reverse the second half
        prev = None
        while slow:
            slow.next,slow,prev = prev,slow.next,slow
        #prev now is the head of reversed second half
        
        #compare the first part and the second part
        first = head
        second = prev
        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.