234. Palindrome Linked List

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if head is None:
            return True
        # count how many nodes in linked list
        count = 0
        cur = head
        while(cur):
            count += 1
            cur = cur.next
            
        # get second half head
        if count % 2 == 0:
            targetCount = count / 2 + 1
        else:
            if count == 1:
                return True
            targetCount = (count + 1) / 2 + 1
        # count = 1 # don't use same name for different meaning in one function
        target = head
        # while(count < targetCount):
        for i in range(targetCount - 1): # f*king forget colon again !??
            # # 1 2 3 4 5
            # u a b c d e 
            target = target.next
            # count += 1 # control flow criterion needs to be paid double attention
            
        # reverse second half and check
        reversedTarget = self.reverse(target) # remember to add self. for calling class function
        cur = head
        curT = reversedTarget
        # while (cur and curT): # for checking whether cur and curT having None at the begining, but it is not possible, because we have already checked count == 0 and count == 1 two situations ahead.
        for i in range(count / 2):
            if cur.val != curT.val:
                return False
            cur = cur.next
            curT = curT.next
        # if cur or curT: # for checking first half and second half are not same length. But this is problemitic, because is coutn is odd number, first half will always have one more node than the second half.
        #     return False
        # else:
        #     return True
        return True
        
    def reverse(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        pre = None
        cur = head
        while(cur):
            temp = cur.next
            cur.next = pre
            pre = cur
            cur = temp
        return pre
            
        
        

Note:

  1. Combine easy tasks into solving a medium one. e.g. using reverse here is ez to implement and quite helpful.

  2. COLONS !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  3. remember use == but not =

  4. when reversing linked list, set pre = None is ez to understand.

Last updated