https://leetcode.com/problems/palindrome-linked-list/


understanding


这里涉及given a head node, find the middle point of a linked list.

要注意 

1, 找到middle point之后,不需要分奇数和偶数长度,只需要知道middle.next肯定就是要reversed的linked list的head

2.    reverse之后,只需要一个从头一个从尾,逐个比较就行,直到某一个指针指向None。


ref: 

http://bookshadow.com/weblog/2015/07/10/leetcode-palindrome-linked-list/

my code:

class Solution(object):
    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        i, j= head, head
        
        if not head:
            return True
        if not head.next:
            return True
        
        while i.next and i.next.next:
            i = i.next.next
            j = j.next

        cur, pre = j.next, None # pre can get the head node of the reversed linkedlist
        while cur:
            next_node = cur.next
            cur.next = pre
            pre, cur = cur, next_node
        new_head = pre
        
        p1,p2 = head, new_head
        
        
        while p1 and p2 and p1.val == p2.val:
            p1,p2 = p1.next, p2.next
        if not p1 or not p2:
            return True
        else:
            return False